'var that = this;' 是什么意思 在 JavaScript 中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4886632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:36:53  来源:igfitidea点击:

What does 'var that = this;' mean in JavaScript?

javascriptthis

提问by Chris

In a JavaScript file I saw:

在我看到的 JavaScript 文件中:

function Somefunction(){
   var that = this; 
   ... 
}

What is the purpose of declaring thatand assigning thisthis to it?

声明that并将其分配this给它的目的是什么?

回答by lonesomeday

I'm going to begin this answer with an illustration:

我将用一个插图开始这个答案:

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
    });
});

My answer originally demonstrated this with jQuery, which is only very slightly different:

我的回答最初用 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
    });
});

Because thisfrequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to thatallows you still to access the original value of this.

因为this通过调用新函数更改作用域时经常会发生变化,所以无法通过使用它来访问原始值。将其别名为 tothat允许您仍然访问this.

Personally, I dislike the use of thatas the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I alwaysuse a more descriptive alias. In my examples above, I'd probably use clickedEl.

就个人而言,我不喜欢使用thatas 别名。它所指的内容很少是显而易见的,尤其是当函数长度超过几行时。我总是使用更具描述性的别名。在我上面的例子中,我可能会使用clickedEl.

回答by El Ronnoco

From Crockford

克罗克福德

By convention, we make a private thatvariable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes thisto be set incorrectly for inner functions.

按照惯例,我们将该变量设为私有。这用于使对象可用于私有方法。这是为在ECMAScript的语言规范的错误导致一种变通方法这个不正确地对内部函数来设定。

JS Fiddle

JS小提琴

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);

This alerts...

这提醒...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

用途那认为它叫戴夫

UsesThis 认为它​​被称为 undefined

回答by Waylon Flinn

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another thisautomatically gets set to the global scope. This can be confusing because you expect thisto have the same value as in the outer function.

这是一种使内部函数(在其他函数中定义的函数)更像它们应该工作的方法。在 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();

};

This is specifically a problem when you create a function as a method of an object (like car.startin the example) then create a function inside that method (like activateStarter). In the top level method thispoints to the object it is a method of (in this case, car) but in the inner function thisnow points to the global scope. This is a pain.

当您创建一个函数作为对象的方法(如car.start示例中)然后在该方法中创建一个函数(如activateStarter)时,这是一个特别的问题。在顶级方法this指向对象,它是(在本例中,car)的方法,但在内部函数中this现在指向全局范围。这是一种痛苦。

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name thatis used. It's an easily recognizable convention for overcoming a shortcoming in the language.

创建一个在两个范围内按约定使用的变量是解决这个非常普遍的 javascript 问题的解决方案(尽管它在 jquery 函数中也很有用)。这就是使用非常通用的名称的that原因。这是一个易于识别的约定,用于克服语言中的缺点。

Like El Ronnoco hints at Douglas Crockfordthinks this is a good idea.

就像 El Ronnoco 暗示道格拉斯·克罗克福德(Douglas Crockford)认为这是个好主意一样。

回答by Adela

The use of thatis not really necessary if you make a workaround with the use of call()or apply():

使用的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);
};

回答by Ahmad Ajmi

Sometimes thiscan refer to another scope and refer to something else, for example suppose you want to call a constructor method inside a DOM event, in this case thiswill refer to the DOM element not the created object.

有时this可以引用另一个范围并引用其他内容,例如假设您想在 DOM 事件中调用构造函数方法,在这种情况下this将引用 DOM 元素而不是创建的对象。

HTML

HTML

<button id="button">Alert Name</button>

JS

JS

var Person = function(name) {
  this.name = name;
  var that = this;
  this.sayHi = function() {
    alert(that.name);
  };
};

var ahmad = new Person('Ahmad');
var element = document.getElementById('button');
element.addEventListener('click', ahmad.sayHi); // => Ahmad

Demo

演示

The solution above will assing thisto thatthen we can and access the name property inside the sayHimethod from that, so this can be called without issues inside the DOM call.

上面的解决方案将this帮助that我们可以访问方法中的 name 属性sayHifrom that,因此可以在 DOM 调用中调用它而不会出现问题。

Another solution is to assign an empty thatobject and add properties and methods to it and then return it. But with this solution you lost the prototypeof the constructor.

另一种解决方案是分配一个空that对象并为其添加属性和方法,然后返回它。但是使用此解决方案,您丢失prototype了构造函数的 。

var Person = function(name) {
  var that = {};
  that.name = name;
  that.sayHi = function() {
    alert(that.name);
  };
  return that;
};

回答by stacksonstacksonstacks

Here is an example `

这是一个例子`

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

因此,您可以看到 this 的值是两个不同的值,具体取决于您定位的 DOM 元素,但是当您将“that”添加到上面的代码时,您会更改您所定位的“this”的值。

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700");//Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

..... $(that).css("background-color", "#ffe700"); //这里“that”的值是“.our-work-group > p > a”,因为 var that = this; 所以即使我们在“this”= '.our-work-single-page',我们仍然可以使用“that”来操作之前的DOM元素。