【问题标题】:Javascript - destructuring object - 'this' set to global or undefined, instead of objectJavascript - 解构对象 - 'this' 设置为全局或未定义,而不是对象
【发布时间】:2017-05-26 23:35:27
【问题描述】:

我有一个具有两个功能的对象,foobarbar 致电 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


【解决方案1】:

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

相同
var foo = functions.foo;
var bar = functions.bar;

函数不绑定到它们的“父”对象。 this 所指的内容取决于函数的调用方式。 foo()functions.foo() 是调用函数的两种不同方式,因此 this 在每种情况下都有不同的值。

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

How does the "this" keyword work?

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多