2016-11-28 20 views
0
function Test(){ 
    var aVariable =1; 
    this.bVaribale = 2; 
    this.say = function(){ 
     console.log(this.bVaribale); 
    } 
} 

var t1 = new Test(); 
var t2 = Test.constructor(); 

t1.say(); 
t2.say(); 

新的最后行调用函数的构造产生Uncaught TypeError: t2.say is not a function(…)如何通过构造属性,而不是

如何通过constructor属性调用函数的构造?

+0

不不不不不。 'Test'是一个'Function'实例 – Oriol

+0

* Test.constructor *是内置的Function构造函数。也许你的意思是't1.constructor'。但将* Test *作为函数调用并不会将* this *设置为* Test *的新实例,并且它会返回* undefined *,而不是* this *。 – RobG

回答

0

应该是...

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, []); 

...这似乎已经在主流浏览器中实现。

0

constructor属性指向用于构造您访问constructor的实例的构造函数。

这不是内部[[Construct]]方法!

由于TestFunctionTest.constructor === Function

您可能希望Reflect.construct代替:

Reflect.construct(Test, []) 
0

这不叫自己的财产像一个内置属性的最佳做法。 为了达到你的目标,你可以做这样的事情:

function Test() { 
    return { 
    create: function() { 
     return new Test(); 
    } 
    }; 
} 

,并调用它

Test().create()