我什么时候应该使用 "that" 的 Douglas Crockfords 实现?
When should I used Douglas Crockfords implementation of "that"?
在 Douglas Crockford 的文章 Private Members in Javascript 中,他使用变量 "that" 来引用 "this",以便在 class 的特权方法中使用。我一直在我的代码中使用 "this.publicMember",它似乎工作正常。我认为你真正需要使用 "that" 的唯一时间是如果你正在调用 "this" 明显不同的函数,即从 setTimeout 调用它。我什么时候应该使用/不使用 "that" ?
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
return dec() ? that.member : null;
};
}
对战:
this.service = function () {
return dec() ? this.member : null;
};
在 JS 中,有很多场景 this
的值与外部块中的 this
的值不同:
如果刚好需要用到this
的外块值,那么就用that
.
他在文章中写道:
By convention, we make a private that
variable. This is used to make the object available to the private methods.
然后他就到处使用 that
来避免未绑定函数的问题(比如你提到的 setTimeout
)并且能够轻松地在私有和私有之间切换 "method"特权。由于无论如何该方法已经是特定于实例的(不是从原型继承而来的),因此绑定它并访问另一个闭包变量确实没有什么坏处。
在 Douglas Crockford 的文章 Private Members in Javascript 中,他使用变量 "that" 来引用 "this",以便在 class 的特权方法中使用。我一直在我的代码中使用 "this.publicMember",它似乎工作正常。我认为你真正需要使用 "that" 的唯一时间是如果你正在调用 "this" 明显不同的函数,即从 setTimeout 调用它。我什么时候应该使用/不使用 "that" ?
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
this.service = function () {
return dec() ? that.member : null;
};
}
对战:
this.service = function () {
return dec() ? this.member : null;
};
在 JS 中,有很多场景 this
的值与外部块中的 this
的值不同:
如果刚好需要用到this
的外块值,那么就用that
.
他在文章中写道:
By convention, we make a private
that
variable. This is used to make the object available to the private methods.
然后他就到处使用 that
来避免未绑定函数的问题(比如你提到的 setTimeout
)并且能够轻松地在私有和私有之间切换 "method"特权。由于无论如何该方法已经是特定于实例的(不是从原型继承而来的),因此绑定它并访问另一个闭包变量确实没有什么坏处。