【发布时间】:2017-05-26 23:35:27
【问题描述】:
我有一个具有两个功能的对象,foo 和 bar。 bar 致电 foo。
通常,当bar 使用this.foo() 时,这可以正常工作。但是,在解构对象时,this 不再引用该对象。在下面的代码 sn-p 中,它是未定义的。当我在 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)
【问题讨论】:
-
呃,是吗?不要解构需要在对象上调用的方法。你要什么?
标签: ecmascript-6 this destructuring