簡體   English   中英

如何通過構造函數屬性而不是new調用函數構造函數

[英]How to invoke function constructor through constructor property instead of new

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(…)

如何通過構造函數屬性調用函數構造函數?

應該...

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

...似乎已經在主要瀏覽器中實現了。

constructor屬性指向用於構造您要在其上訪問constructor函數的實例的constructor

這不是內部的[[Construct]]方法!

由於Test是一個Function ,因此Test.constructor === Function

您可能需要Reflect.construct

Reflect.construct(Test, [])

調用自己的屬性(如內置屬性)不是最佳做法。 為了達到目標,您可以執行以下操作:

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

並稱之為

Test().create()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM