Javascript - 解构对象 - "this"设置为全局或未定义,而不是对象



我有一个包含两个函数的对象,foobarbar打电话给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)

解构与将属性分配给局部变量相同。 即在您的情况下,它将

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

函数不绑定到其"父"对象。this指的是什么取决于函数的调用方式。 foo()functions.foo() 是调用函数的两种不同方式,因此this在每种情况下都有不同的值。

这对 ES6 或解构来说并不是什么新鲜事,JavaScript 一直都是这样工作的。

请参阅"this"关键字如何工作?。

最新更新