【发布时间】:2018-06-22 18:11:11
【问题描述】:
我只是在玩弄并试图弄清楚 this 对象是如何工作的,以及如何使用 bind 函数传递范围上下文。
到目前为止,我已经到了这一点(检查下面的代码),并发现我可以将绑定与对象函数一起使用,以便将 myObject 的范围传递给对象函数 run强>。
第一个问题:
为什么我需要使用 this.first() 而不是 first()?
因为否则它仍然使用 second's 上下文。
myObject = {
first: function(){ console.log("myObject's first()")},
second: function(){
function first(){ console.log("second's first()")};
let run = function(){ this.first()}.bind(this);
run();
},
}
myObject.second()
接下来,我想把它提升到一个新的水平,我在 second 中嵌套了另一个函数(检查代码)。 第二个问题:
从下面的代码中我得到错误 错误:this.first is not a 函数,以及我是否调用 .bind(this) 会给出 同样的错误,任何线索为什么会发生这种情况?
myObject = {
first: function(){ console.log("myObject's first()")},
second: function(){
function first(){ console.log("second's first()")};
function secondx2(){
function first(){ console.log("secondx2's first()")};
let run = function(){ this.first()}
run();
}
secondx2();
},
}
myObject.second()
【问题讨论】:
-
this和变量范围几乎没有关系。Function#bind返回一个新函数,该函数使用特定的this值调用其目标函数,但完全不影响作用域,例如call和apply。 -
你打电话给
secondx2(),但没有提供this。做secondx2.call(this);注意:考虑使用箭头函数,它使用词法this的方式可能更适合你的情况。 -
@Ryan ya,但是为什么我不能在第二个 sn-p 中运行 this.first()?
-
@user3676224:由 trincot 的评论和副本解释。
标签: javascript this scopes