2016-01-31 61 views
2

我正在查看ES6功能和Symbol類型爲我創建了一個問題。檢測構造函數(符號) - ES6

使用ES6我們不能在Symbol()上應用new運營商。當我們這樣做時,它會引發錯誤。它會檢查函數是否被用作構造函數。那麼,它如何檢查函數是否被用作構造函數或不在幕後? (實施可能會根據平臺而變化。)

您能分享任何示例實施嗎?

+0

嗯,這是一個本地函數,那麼你將如何處理「示例實現」? – Bergi

回答

1

當函數被稱爲構造函數,this成爲此函數的原型。您可以檢查它並引發錯誤:

function NotConstructor() { 
    if(this instanceof NotConstructor) { 
    throw new Error('Attempt using function as constructor detected!') 
    } 
    console.log('ok'); 
} 

NotConstructor(); // 'ok' 
new NotConstructor(); // throws Error 

此外,請參閱相關的問題How to detect if a function is called as constructor?,它有更多的細節,關於它的見解。

3

爲了與new一起使用,函數對象必須具有內部[[Construct]]屬性。雖然普通的用戶自定義函數確實有它自動設置,這不是內置的人一定是真的:

new Symbol() // nope 
new Math.cos() // nope 

ES6箭頭和方法沒有任何[[Construct]]

fn = (x) => alert(x); 
new fn(); // nope 

class Y { 
    foo() { 
    } 
} 

let y = new Y(); 
new y.foo(); // nope