我已经阅读了有关使用apply
和new
即时创建对象的重要问题。
确切的问题是:
我想创建一个对象实例(通过new运算符),但是将任意数量的参数传递给构造函数。这可能吗
我对所选答案有疑问:
/*1*/ function construct(constructor, args) {
/*2*/ function F() {
/*3*/ return constructor.apply(this, args);
/*4*/ }
/*5*/ F.prototype = constructor.prototype;
/*6*/ return new F();
/*7*/ }
(工作jsbin)
一切都好。
但
我试图将第3行移动到第6行:所以最终输出是:
/*1*/ function construct(constructor, args) {
/*2*/ // function F() {
/*3*/ // return constructor.apply(this, args);
/*4*/ // }
/*5*/ //F.prototype = constructor.prototype;
/*6*/ return new constructor.apply(this, args);
/*7*/ }
(非工作jsbin)
我的问题是为什么第二个示例不起作用?有什么不同 ?
我所做的就是将代码从一个地方移到另一个地方。
例:
function calc()
{
function a() {return 4};
return a(); // I could easily do `return 4` instead...;
}
问题:
为什么移动的代码不起作用?
您声明:
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
应该与:
function construct(constructor, args) {
return new constructor.apply(this, args);
}
但这实际上在几个基本方面有所不同:
1. constructor.apply
是本机非构造函数。New
只能从构造函数创建对象:
可以通过创建对象的构造函数来创建对象,然后通过为对象的属性分配初始值来执行初始化所有或部分对象的代码。每个构造函数都是一个函数,该函数具有名为“ prototype”的属性,该属性用于实现基于原型的继承和共享属性。通过在新表达式中使用构造函数来创建对象[...]
http://www.ecma-international.org/ecma-262/5.1/#sec-4.2.1
F
另一方面是一个功能对象。所有函数对象都可以用作构造函数。
注意:Alon Gubkin说new constructor.apply(this, args)
不起作用,因为constructor.apply(this, args).prototype
未定义。这不是真的。如果是因为那将意味着函数调用运算符的优先级比新运营商较高(即“新constructor.apply(这一点,参数)相同的新(constructor.apply(这一点,参数))`),这是不对。
2.即使constructor.apply
是构造函数,也不会与相同constructor.prototype
。的原型F
设置为constructor's
原型,以确保通过new运算符与组合创建的所有对象都与与组合创建的对象F
相同constructor
。之间唯一的区别F
,并constructor
为他们不同的功能,从而可以用于F
调用constructor
以更灵活的方式。
constructor.apply.prototype
可以实际设置为constructor.prototype
,但constructor.apply
仍不能使用构造函数。
3.在您的new constructor.apply(this, args)
语句中,this
参数不是指向新创建的对象,而是指向this
本地范围。因此,即使您可以将apply
函数用作将apply's
原型设置为constructor's
原型的构造函数,您仍然会将错误传递this
给constructor
函数。
注意:在您的示例中
function calc()
{
function a() {return 4};
return a(); // I could easily do `return 4` instead...;
}
return
可以与任何类型的表达式一起使用,而new
不能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句