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

标签 ecmascript-6 this destructuring

我有一个具有两个函数的对象,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)

最佳答案

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

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

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

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

参见How does the "this" keyword work? .

关于ecmascript-6 - Javascript - 解构对象 - 'this' 设置为全局或未定义,而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41603396/

相关文章:

javascript - 解构数组中的嵌套对象

javascript - ES6 转译器中的导入/导出

java - 下面的程序中 this(1) 和 this(2) 的目的是什么?

Javascript 无法从使用此调用的方法设置属性

C++将指向当前对象的指针传递给函数

typescript - 解构空数组时,TS 不会推断可能未定义

javascript - 这种默认参数和解构的特殊场景是如何工作的?

javascript - 如何在有条件的情况下在另一个组件正下方的无状态组件上呈现函数?

node.js - ES6 中使用 import { a } from 'somewhere' 和 import a from 'somewhere' 有什么区别?

javascript - ES6 做 for of get prototype values - 如何检查 hasownproperty