我知道 JavaScript 会自动为每个函数/方法分配参数 this
,并且 this
绑定(bind)到包含它的对象。
方法是存储为对象属性的函数。因此在方法中,this
可用于修改或检索包含它的对象的值。但是,如果该方法作为函数调用,而不是作为对象的属性调用,则 this
将绑定(bind)到全局,而不是对象。
解决方法是分配:
var that = this;
在方法内部,以便内部函数可以通过变量 that
访问 this
。
我的问题是:为什么需要这种解决方法?总不能一直用方法吧?为什么要将一个非常好的方法作为内部函数调用,然后必须创建另一个变量,以便它具有如果它作为方法调用时本来应该具有的访问权限?
我一定在这里遗漏了一些重要的东西,如果有一个愚蠢的问题标签,我会使用它。 (有人可以做一个吗?)
最佳答案
希望我能正确理解您的问题。因为你的表达方式有点令人费解 - f*** XD。
但据我了解。我将回答您的问题,如“我们将 that
技巧用于什么?”。
所以这是一个非常健康的对象。
var myobject = {
firstMethod : function(){
this.secoundMethod(); // calls the other method
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
现在我想做一些 jquery 魔术(或任何其他具有回调函数的东西)。 我打算使用 jQuery,但可以随意做其他事情。
var myobject = {
firstMethod : function(){
var _this = this ;
this.secoundMethod(); // calls the other method
$('.myClass').animate({'width':300} , 300 , function(){
// this is a call back functon which will be called as soon as the animation ends
// the problem is that if i call @var : `this` , it wont work because im in
// another scope other than the firstMethod .
// so the following will throw an error .
this.secoundMethod(); // error
// to solve this you need the @var : `that` , or in my case i love it to be _this
_this.scoundMethod() // this will work .
})
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
所以主要是 _this
(在我的例子中)用于限定事物的范围。所以我可以访问其他范围内的对象范围。
老实说,我在其他地方使用过这个技巧(在大约 99% 的情况下);
即使剩下的 1% 也基本上是相同的想法,但嵌套更深或有很多闭包之类的东西。
这有多危险?!
嗯,这取决于你有多聪明。这是另一个大脑示例
var myobject = {
firstMethod : function(){
var _this = this ,
someObject : {
firstMethod : function(){
this.scoundMethod(); // if you log this you will get 'the wrong method'.
_this.scoundMethod(); // in here you get 'hi from method 2'.
},
scoundMethod : function(){
return 'the wrong method';
}
};
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
如您所见,这很危险,不是因为它不起作用,而是因为它起作用了。因为如果你有类似命名的函数并且你有一个错过的范围,你最终会花费数小时和数小时的挖掘时间。如果你没有那个 .. 你会得到一个很好的错误,你可以立即修复
这能持续多久。
你想嵌套多少就嵌多少。但是会有后果(很少吧?!)。 享受以下,不要在家里尝试。
var myobject = {
firstMethod : function(){
var _this = this ,
someVar = [1 , 2 , 3 ] ;
this.scoundMethod(function(){
var that = this;
$.each(someVar,function(elementName){
var them = this;
$('.'+elementName).animate({} , 300 , function(){
console.log(them) // logs the element
console.log(_this.scoundMethod()) // logs 'hi from method 2'
})
})
}
},
scoundMethod : function(){
return 'hi from method 2' ;
}
}
其他资源:
Scope and this in JavaScript - jack ·富兰克林
“this” and “that”: understanding execution context in javascript - stevenmhunt
希望我已经让它变得简单了。而且我没有回答错误的问题。
关于javascript - 为什么调用内部函数而不是方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18919849/