应该是...
function Test(){
this.bVariable = 2;
this.say = function(){
console.log(this.bVariable);
}
}
var t1 = new Test();
var t2 = new Test.prototype.constructor();
// or var t2 = new t1.constructor();
// both work
t1.say();
t2.say();
见,Test
本身是一个很好的对象(函数,具体而言)。随着Test.constructor
你访问这个对象的构造函数 - 全球Function
功能:
console.log(Test.constructor === Function); // true
你似乎在寻找与Test
创建对象的constructor
财产。这意味着你要么查询t1.constructor
(如果你知道这些对象),或Test.prototype
如果你知道函数本身。后一种情况似乎很奇怪(通过something.prototype.constructor
访问something
有什么好处?)
请注意,您仍然应该使用new
关键字来设置正确的上下文。另一种方法是使用ES6 Reflect API - 更具体,Reflect.construct:
var t2 = Reflect.construct(Test, []);
...这似乎已经在主流浏览器中实现。
不不不不不。 'Test'是一个'Function'实例 – Oriol
* Test.constructor *是内置的Function构造函数。也许你的意思是't1.constructor'。但将* Test *作为函数调用并不会将* this *设置为* Test *的新实例,并且它会返回* undefined *,而不是* this *。 – RobG