2017-01-12 55 views
0

我有一個對象,具有兩個函數foobarbar調用foo。 通常情況下,當bar使用this.foo()時,此工作正常。但是,解構對象時,this不再引用該對象。在下面的代碼片段中,它是未定義的。當我在chrome中運行它時,它指的是window對象。Javascript - 解構對象 - 'this'設置爲全局或未定義,而不是對象

預計輸出

func1() 
foo 
objectValue 
foo 
bar 

func2() 
foo 
objectValue 
foo 
bar 

實際輸出

func1() 
foo 
objectValue 
foo 
bar 

func2() 
foo 
globalValue (or Uncaught TypeError, in the case of the code snippet, which breaks here) 
Uncaught TypeError: this.foo is not a function (in the case of chrome, which breaks here) 

*注:重現鉻,改變let val = 'globalValue'val = 'globalValue'

let val = 'globalValue' 
 

 
let functions = { 
 
    val : 'objectValue', 
 
\t foo : function(){ 
 
\t \t console.log('foo') 
 
\t }, 
 
\t bar : function(){ 
 
\t \t console.log('this.val: ' + this.val) 
 
\t \t this.foo() 
 
\t \t console.log('bar') 
 
\t } 
 
} 
 

 
class Class { 
 
\t func1(functions){ 
 
\t \t console.log('func1()') 
 
\t \t functions.foo() 
 
\t \t functions.bar() 
 
\t } 
 
\t 
 
\t func2({foo, bar}){ 
 
\t \t console.log('func2()') 
 
\t \t foo() 
 
\t \t bar() 
 
\t } 
 
} 
 
let instance = new Class() 
 

 
instance.func1(functions) 
 
console.log('\n') 
 
instance.func2(functions)

+0

呃,是嗎?不要解構你需要調用對象的方法。你在問什麼? – Bergi

回答

1

解構與將屬性分配給局部變量相同。即在你的情況下,它將是相同的

var foo = functions.foo; 
var bar = functions.bar; 

函數沒有綁定到他們的「父」對象。 this引用的內容取決於函數的調用方式。 foo()functions.foo()是調用函數的兩種不同方式,因此this在每種情況下都有不同的值。

這對ES6或解構沒有什麼新意,JavaScript一直都是這樣工作的。

參見How does the "this" keyword work?

+0

感謝您的答覆和參考,我會讀它。 –

相關問題