2016-11-11 70 views
0

我正在運行節點6.9.1。爲什麼super使用方法語法,但不使用屬性語法?

我定義了一個基本對象是這樣的:

const base = { 
    value : 10, 
    getFinalValue : function() { 
    return this.value 
    } 
} 

現在我想要定義爲getFinalValue方法的修改。

我第一次嘗試使用新的ES6 super關鍵字:

const modifier = Object.create(base) 
modifier.getFinalValue = function() { 
    return super.getFinalValue() + 20 
} 

然而,上面的代碼給我下面的錯誤:

> SyntaxError: 'super' keyword unexpected here 

的我想:

// With Object.defineProperties within Object.create 
const modifier = Object.create(base, { 
    getFinalValue : { 
    value : function() { 
     return super.getFinalValue() + 20 
    } 
    } 
}) 

// And with Object.setPrototypeOf 

const modifier = { 
    getFinalValue : function() { 
    return super.getFinalValue() + 20 
    } 
} 

Object.setPrototypeOf(modifier, base) 

結果是一樣的錯誤。

不過,如果我使用新的方法,ES6語法:

const modifier = { 
    getFinalValue() { 
    return super.getFinalValue() + 20 
    } 
} 

Object.setPrototypeOf(modifier, base) 

modifier.getFinalValue() // 30 (yay!) 

它工作得很好。

如果我使用Object.getPrototypeOf而不是super,它的工作原理使用屬性語法:

const modifier = { 
    getFinalValue: function() { 
    return Object.getPrototypeOf(this).getFinalValue.call(this) + 20 
    } 
} 

Object.setPrototypeOf(modifier, base) 

modifier.getFinalValue() // 30 (Yay!) 

有人能向我解釋爲什麼會發生這種情況?

P.S .:是的,我知道我在混合使用ES5和ES6語法,但這是有意的。

回答

0

However, if I use the new ES6 method syntax ... It works just fine.

這就是要點。不允許在常規功能中使用super。該specification狀態

It is a Syntax Error if FormalParameters Contains SuperProperty is true.

It is a Syntax Error if FunctionBody Contains SuperProperty is true.

It is a Syntax Error if FormalParameters Contains SuperCall is true.

It is a Syntax Error if FunctionBody Contains SuperCall is true.

的原因是,僅方法場在他們的環境記錄,允許JS引擎來解決super值設置。方法聲明不僅僅是語法糖。

+0

請問您是否可以詳細說明您的問題,甚至提供超出規格的鏈接?謝謝。 –

相關問題