Javascript 什么是;这";指向子函数中的方法?
我写了一个做作的脚本,说明了我不明白的地方:Javascript 什么是;这";指向子函数中的方法?,javascript,this,Javascript,This,我写了一个做作的脚本,说明了我不明白的地方: var newObject = {} newObject.testAttribute = "I'm newObject"; newObject.someMethod = function(){ console.log(this.testAttribute); var sub_function = function(){ console.log(this.testAttribute); } sub
var newObject = {}
newObject.testAttribute = "I'm newObject";
newObject.someMethod = function(){
console.log(this.testAttribute);
var sub_function = function(){
console.log(this.testAttribute);
}
sub_function();
}
newObject.someMethod();
在sub_函数中,由于闭包,我希望“this”引用对象newObject,但是控制台上的输出是
"I'm newObject"
undefined
此
表示上下文。每个函数都有自己的上下文,除非您直接指定它,例如
this.myfunction = function(){}
或
你可以了解更多我的问题被昆汀标记为重复,但它没有说明我重复了什么问题。我现在看到了。相当长的帖子。而且含糊不清,而我的问题非常具体。我建议更改你的用户名和头像,因为这可能会被认为是冒犯性的。好的。我不知道如何做这两件事,但我会调查的。
myfunction.bind(this)