Chr*_*ris 346 javascript this
在JavaScript文件中,我看到:
function Somefunction(){
var that = this;
...
}
Run Code Online (Sandbox Code Playgroud)
声明that
和分配给它的目的是什么this
?
lon*_*day 478
我将以一个例子开始这个答案:
var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
// this is a reference to the element clicked on
var that = this;
colours.forEach(function() {
// this is undefined
// that is a reference to the element clicked on
});
});
Run Code Online (Sandbox Code Playgroud)
我的回答最初用jQuery证明了这一点,它只是略有不同:
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
Run Code Online (Sandbox Code Playgroud)
由于this
通过调用新函数更改范围时经常更改,因此无法使用它来访问原始值.将其别名化以that
允许您仍然可以访问原始值this
.
就个人而言,我不喜欢使用that
别名.很少有人明白它的含义,特别是如果函数长于几行.我总是使用更具描述性的别名.在我上面的例子中,我可能会使用clickedEl
.
El *_*oco 105
按照惯例,我们做一个私有的是 可变的.这用于使对象可用于私有方法.这是为在ECMAScript的语言规范的错误导致一种变通方法这个不正确地对内部函数来设定.
function usesThis(name) {
this.myName = name;
function returnMe() {
return this; //scope is lost because of the inner function
}
return {
returnMe : returnMe
}
}
function usesThat(name) {
var that = this;
this.myName = name;
function returnMe() {
return that; //scope is baked in with 'that' to the "class"
}
return {
returnMe : returnMe
}
}
var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
"UsesThis thinks it's called " + usesthis.returnMe().myName);
Run Code Online (Sandbox Code Playgroud)
这提醒......
用途认为它叫做戴夫
UsesThis认为它被称为undefined
Way*_*inn 84
这是一个让内部函数(在其他函数中定义的函数)更像它们应该工作的hack.在javascript中,当你在另一个函数中定义一个函数时,this
自动将其设置为全局范围.这可能会令人困惑,因为您希望this
具有与外部函数中相同的值.
var car = {};
car.starter = {};
car.start = function(){
var that = this;
// you can access car.starter inside this method with 'this'
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to the global scope
// 'this.starter' is undefined, so we use 'that' instead.
that.starter.active = true;
// you could also use car.starter, but using 'that' gives
// us more consistency and flexibility
};
activateStarter();
};
Run Code Online (Sandbox Code Playgroud)
当您将函数创建为对象的方法(如car.start
示例中),然后在该方法内创建函数(如activateStarter
)时,这是一个特别的问题.在顶级方法中this
指向对象它是(在这种情况下car
)的方法,但在内部函数中this
现在指向全局范围.这是一种痛苦.
在两个作用域中按惯例创建要使用的变量是javascript的这个非常普遍的问题的解决方案(尽管它在jquery函数中也很有用).这就是使用非常通用的声音名称的that
原因.这是一个容易识别的惯例,克服了语言的缺点.
就像El Ronnoco对Douglas Crockford的暗示一样,这是一个好主意.
小智 8
使用的that
是不是真的有必要,如果你与使用的解决办法call()
或apply()
:
var car = {};
car.starter = {};
car.start = function(){
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to our main object
this.starter.active = true;
};
activateStarter.apply(this);
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
114433 次 |
最近记录: |