一个方法可以return一个新对象吗?
Can a method return a new object?
如下:
function AnObject () {}
AnObject.alloc = function () { return new this }
var obj1 = AnObject.alloc();
相当于:
var object1 = new AnObject();
同于:
var obj1 = new AnObject().init();
var obj2 = AnObject.alloc().init();
大多数时候,是的。
第三个不是 a === b
等效的,它们是 typeof a === typeof b
等效的,但是是的。
需要注意的一个关键事项是,一旦您停止像 Java < 8 那样对待它,由于 [=44= 中 this
的性质,您可能会自找麻烦]脚本。
doSomethingAsync()
.then(AnObject.alloc) // boom!
.then(useInstance);
new AnObject()
总是有效的地方
var getObj = AnObject.alloc;
var obj = getObj( );
不会。
也不会:
$.ajax( ).success(AnObject.alloc);
因为 this
是在调用时确定的,而不是在定义方法时绑定(或者在最后一种情况下,甚至被引用,因为它被提供给回调)。
您可能会考虑:
AnObject.alloc = function (config) { return new AnObject(config); };
现在防弹了。
或者,有一个通用的 alloc
方法,bind
每个构造函数。
function alloc (config) { return new this(config); }
AnObject.alloc = alloc.bind(AnObject);
AnotherObject.alloc = alloc.bind(AnotherObject);
现在它是防弹的。
如下:
function AnObject () {}
AnObject.alloc = function () { return new this }
var obj1 = AnObject.alloc();
相当于:
var object1 = new AnObject();
同于:
var obj1 = new AnObject().init();
var obj2 = AnObject.alloc().init();
大多数时候,是的。
第三个不是 a === b
等效的,它们是 typeof a === typeof b
等效的,但是是的。
需要注意的一个关键事项是,一旦您停止像 Java < 8 那样对待它,由于 [=44= 中 this
的性质,您可能会自找麻烦]脚本。
doSomethingAsync()
.then(AnObject.alloc) // boom!
.then(useInstance);
new AnObject()
总是有效的地方
var getObj = AnObject.alloc;
var obj = getObj( );
不会。
也不会:
$.ajax( ).success(AnObject.alloc);
因为 this
是在调用时确定的,而不是在定义方法时绑定(或者在最后一种情况下,甚至被引用,因为它被提供给回调)。
您可能会考虑:
AnObject.alloc = function (config) { return new AnObject(config); };
现在防弹了。
或者,有一个通用的 alloc
方法,bind
每个构造函数。
function alloc (config) { return new this(config); }
AnObject.alloc = alloc.bind(AnObject);
AnotherObject.alloc = alloc.bind(AnotherObject);
现在它是防弹的。