我有一个具有两个函数的对象,foo
和 bar
。 bar
调用 foo
。
通常,当 bar
使用 this.foo()
时,这可以正常工作。但是,当解构该对象时,this
不再引用该对象。在下面的代码片段中,它是未定义的。当我在 chrome 中运行它时,它引用 window
对象。
预期输出
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)
*注意:要在 Chrome 中重现,请将 let val = 'globalValue'
更改为 val = 'globalValue'
let val = 'globalValue'
let functions = {
val : 'objectValue',
foo : function(){
console.log('foo')
},
bar : function(){
console.log('this.val: ' + this.val)
this.foo()
console.log('bar')
}
}
class Class {
func1(functions){
console.log('func1()')
functions.foo()
functions.bar()
}
func2({foo, bar}){
console.log('func2()')
foo()
bar()
}
}
let instance = new Class()
instance.func1(functions)
console.log('\n')
instance.func2(functions)
最佳答案
解构与将属性分配给局部变量相同。 IE。在你的情况下它会是相同的
var foo = functions.foo;
var bar = functions.bar;
函数不绑定(bind)到它们的“父”对象。 this 指的是什么取决于函数的调用方式。 foo()
和 functions.foo()
是调用函数的两种不同方式,因此 this
在每种情况下都有不同的值。
这对于 ES6 或解构来说并不是什么新鲜事,JavaScript 一直都是这样工作的。
关于ecmascript-6 - Javascript - 解构对象 - 'this' 设置为全局或未定义,而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41603396/