2017-01-12 6 views
0

私はfoobarという2つの機能を持つオブジェクトを持っています。 barfooとなります。 barthis.foo()を使用している場合、通常これはうまく動作します。ただし、オブジェクトを破棄するときは、thisはオブジェクトを参照しません。以下のコードスニペットでは、定義されていません。これをクロムで実行すると、windowオブジェクトが参照されます。Javascript - destructuring object - '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

destructuringは、ローカル変数にプロパティを割り当てるのと同じです。私。あなたの場合、それは同じになるでしょう

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

関数は "親"オブジェクトにバインドされていません。 thisは、どのように関数が呼び出されるかによって異なります。 foo()functions.foo()は、関数を呼び出す2つの異なる方法です。したがって、それぞれthisの値が異なります。

これはES6の新機能ではなく、破壊的でもありません.JavaScriptは常にそのように機能しています。

How does the "this" keyword work?を参照してください。

+0

答えと参考に感謝します。私はそれを読むでしょう。 –

関連する問題