gpt4 book ai didi

javascript - 最好使用 "this"还是 "that"(其中 var that = this)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:50:53 26 4
gpt4 key购买 nike

我是 JavaScript 的新手,我正在清理我下载的一些 JavaScript 代码。此代码中的不一致之处之一是 this 和引用它的局部变量 that 的混合使用。

示例代码片段(jQuery UI 小部件中的私有(private)方法):

_populateLists: function(options) {
//do stuff with this

var that = this;
options.each(function(index) {
//use both this AND that, they are different in this scope
});

//here this and that are the same thing
//I want to be consistent, is one preferable over the other?
},

在整个代码的许多地方,范围是这样的 this === that,即使在同一行代码中,也存在混合用法。

为了可读性和可维护性,使用this还是that更好?

注意:我意识到很多这类事情取决于开发人员的偏好。但在我决定重写代码以使用其中一个之前,我想了解任何推理是否/为什么一个比另一个更受欢迎。

编辑: 在这个脚本中,我认为 唯一 this 被分配给局部变量的原因是它可以被引用从内部闭包内。

最佳答案

this 的值通常分配给局部变量的原因是您可以关闭该值并在嵌套函数中使用它。

this 是一个特殊变量,与普通局部变量有些不同,因为它会自动设置为调用函数的对象(如果有);否则,全局对象。然而,this 的这种内在值(value)由于 jQuery 对 call 的自由使用而有些困惑。和 apply ,它允许调用者指定 this 的值。

在嵌套函数中,this 不继承其父级的 this 的值,就像它通过作用域链继承父级的局部变量一样。

因此,如果我们在嵌套函数中需要它,我们必须将 this 的值存储在局部变量中,例如您示例中的 each 回调.

var a = { fn: function() {
// here, `this` is the object `a`
var x = this;
function b() {
// here, `this` is `window` because `b` is invoked with no context
// ...but we still have access to `x`, whose value would be `a`
}
b();
}};

a.fn(); // by invoking `fn` as a property of `a`, we implicitly set `fn`'s
// `this` to `a`.

// Compare to:
var f = a.fn;
f(); // we now invoke `fn` with no context, so its `this` will be `window`.
a.fn.call(window); // or by specifying context explicitly

当然,当您仍在父作用域中时,this 仍将等于 that(或 self 或其他)。乍一看,两者似乎没有区别,但有一个重要的性能影响:

缩小。如果您将this 分配给局部变量,则对该变量的所有引用都可以减少为一个字符。不能引用 this。比较这个缩小的输出:

function a() {this.w=1;this.x=2;this.y=3;this.z=4;}
function b() {var t=this;t.w=1;t.x=2;t.y=3;t.z=4;}

通过对 this 的 4 次引用,您可以使用变量保存字节。如果无论如何都必须为内部函数捕获 this,在外部函数中使用局部变量而不是 this 可以节省成本,即使只有一个引用也是如此。

关于javascript - 最好使用 "this"还是 "that"(其中 var that = this)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14046682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com