我试图更好地理解 JavaScript 中 that 和 this 的用法。我在这里关注 Douglas Crockford 的教程:http://javascript.crockford.com/private.html http://javascript.crockford.com/private.html但我对一些事情感到困惑。我在下面给出了一个例子,我想知道我是否正确使用了它们:
function ObjectC()
{
//...
}
function ObjectA(givenB)
{
ObjectC.call(this); //is the use of this correct here or do we need that?
var aa = givenB;
var that = this;
function myA ()
{
that.getA(); //is the use of that correct or do we need this?
}
this.getA = function() //is the use of this correct?
{
console.log("ObjectA");
};
}
function ObjectB()
{
var that = this;
var bb = new ObjectA(that); //is the use of that correct or do we need this?
this.getB = function()
{
return bb;
};
that.getB(); //is the use of that correct or do we need this?
}
请注意,这只是一个示例。
this
在 JavaScript 中总是指当前对象,其方法被调用。但有时你需要访问this
更深入地了解你的对象。例如,在回调中。就像这样:
function MyClass() {
this.a = 10;
this.do = function() {
http.get('blablabla', function(data) {
this.a = data.new_a;
});
};
}
这是行不通的,因为this
在回调中可以参考http
,到某个 dom 元素或只是窗口(这确实很常见)。因此,通常的解决方案是定义self
or that
,别名为this
或你的对象,这样你就可以在里面的任何地方引用它。
function MyClass() {
var self = this;
this.a = 10;
this.do = function() {
http.get('blablabla', function(data) {
self.a = data.new_a;
});
};
}
这应该给你视野 why它被使用并且how应该使用它。
没有其他原因(如我错了请纠正我) 要创建特殊变量,您可以使用this
将您的对象发送到其他对象并且做事,很多作业,这样的逻辑,哇...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)