假设我有以下对象构造函数:
function Foo(bar) {
this.bar = bar;
}
如果我在全局范围内运行该函数而不使用new
关键字然后bar
将被设置在任何范围内Foo()
被称为:
var foo = Foo(42);
console.log(bar); // 42
console.log(foo.bar); // ERROR
所以我的想法是做这样的事情:
function Foo(bar) {
if(!(this instanceof Foo)) {
// return a Foo object
return new Foo(bar);
}
this.bar = bar;
}
这样如果我这样做new Foo(42)
or Foo(42)
, 它会always返回一个Foo
object.
Is this ever一个好主意?如果是的话,什么时候?什么时候(以及为什么)避免这种技术是明智的?
当您想要时这可能很有用内部构造一个对象包装器。
一个鲜为人知的库内部使用了这种方法,jQuery。
他们不使用instanceof
不过再接近一点。每次调用 jQuery 时,它都会自动执行以下操作:
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
}
它所做的一切在内部都会引用这个本地副本。在工作结束时,它将其附加到全局范围
window.jQuery = window.$ = jQuery;
所以每次你打电话$()
它内部使用new
。它还假设你这样做not use new
从外部来看,但它并不关心你是否这样做。
edit
jsFiddle Demo http://jsfiddle.net/G69sR/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)