我有一個對象,具有兩個函數foo
和bar
。 bar
調用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)
呃,是嗎?不要解構你需要調用對象的方法。你在問什麼? – Bergi