javascript var vs this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27589494/
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-10-28 07:40:15  来源:igfitidea点击:

javascript var vs this

javascriptvariables

提问by Toniq

If my code looks like this, what is the preferred method of using var vs this?

如果我的代码看起来像这样,那么使用 var 与 this 的首选方法是什么?

function MyObject() {
    var self = this;

    var a = 1;
    this.b = 2;

    var innerMethod = function() {

        logMessage(a); 
        logMessage(self.b); 
    }
}

As I understand, var will survive as long as MyObject lives, so isnt this the same as using this?

据我了解,只要 MyObject 存在,var 就会一直存在,所以这与使用 this 不一样吗?

EDIT:

编辑:

To clarify the question more, I am ONLY interested in accessing variables from inside the object, not from outside.

为了进一步澄清这个问题,我只对从对象内部访问变量感兴趣,而不是从外部访问变量。

回答by A.B

with var ayou cant access the variable outside the scope however assigning with thiscan be accessed when you make an object

var a你不能访问变量外内,但是与分配this,当你做出一个对象可以访问

We add properties to thiswhen we want the properties to exist with the life of the object.We Use var for local variables.

this当我们希望属性在对象的生命周期中存在时,我们添加属性。我们使用 var 作为局部变量。

"I am ONLY interested in accessing variables from inside the object, not from outside."

“我只对从对象内部访问变量感兴趣,而不是从外部访问。”

Answer to this statement is use varif you want to use only inside the function not outside as variable defined with var are accessible only to code in the scope in which they were declared, or in lexically nested scopes.

var如果您只想在函数内部而不是外部使用,则使用此语句,因为使用var 定义的变量只能在声明它们的范围内或词法嵌套范围内的代码中访问。

so as Shomz suggested you can check it as:

因此,正如 Shomz 建议的那样,您可以将其检查为:

var o = new MyObject();

a will be undefined as it is defined with var

a 将是未定义的,因为它被定义为 var

  o.a; // undefined

while b will be return 2 as it is on this

而 b 将按原样返回 2 this

 o.b; // 2

回答by abl

If you define a variable as var, then its scope is limited to the function (it can't be seen from the outside). In OO terms it's somehow like a private property, without actually being a property at all.

如果将变量定义为var,则其作用域仅限于函数(从外部无法看到)。在 OO 术语中,它有点像私有财产,实际上根本不是财产。

If you define a variable as a property (this.name) then it is accessible from the outside.

如果您将变量定义为属性 ( this.name),则可以从外部访问它。

Same goes for functions. Functions declared inside the scope of the function, but not assigned to a property, are only visible from the inside. If you assign a function to a property you are able to access that function from the outside (as long as the property keeps pointing to that function).

函数也是如此。在函数作用域内声明但未分配给属性的函数仅从内部可见。如果将函数分配给属性,则可以从外部访问该函数(只要该属性一直指向该函数)。

function Person(){

    // Declared variable, function scope
    var name = "John";          

    // Property        
    this.surname = "Doe";       

    // Assign anonymous function to property
    this.getName = function(){  
        return name;
    }

    // Assign anonymous function to property
    this.getSurname = function(){ 
        return this.surname;
    }

    // Declare function
    function saluteCasually(){      
        console.log("Hi folks!");
    }

    // Declare function
    function salutePolitely(){          
        console.log("Nice to meet you");
    }

    // Assign (not anonymous) function to property
    this.salutePolitely = salutePolitely;

}

var person = new Person();

console.log(person.name);           // undefined
console.log(person.getName());      // "John"
console.log(person.surname);        // "Doe"
console.log(person.getSurname());   // "Doe"

person.saluteCasually(); // Error: person has not a property "saluteCasually".
person.salutePolitely(); // Prints "Nice to meet you";

person.salutePolitely = function(){ // Properties can be messed with from anywhere!
    console.log("Bananas");
}
person.salutePolitely(); // Prints "Bananas";

回答by Hasan Al-Natour

It depends on what you want , using a VAR inside the function will not make it accessible outside the function scope , but from a performance perspective if you are using objects keep everything inside of it , you have already stored this object in the memory why define another variable again .

这取决于您想要什么,在函数内部使用 VAR 不会使其在函数作用域外可访问,但是从性能角度来看,如果您使用对象将所有内容都保留在其中,您已经将此对象存储在内存中为什么要定义又是一个变量。

as said in the Memory Analysis 101form chrome devtools documentation :

内存分析 101表单 chrome devtools 文档中所述:

Memory can be held by an object in two ways: directly by the object itself, and implicitly by holding references to other objects, and thus preventing them from being automatically disposed by a garbage collector (GC for short).

对象可以通过两种方式持有内存:直接由对象本身持有,以及通过持有对其他对象的引用隐式持有,从而防止它们被垃圾收集器(简称 GC)自动处理。

The size of memory that is held by the object itself is called shallow size. Typical JavaScript objects have some memory reserved for their description and for storing immediate values.

对象本身所持有的内存大小称为浅层大小。典型的 JavaScript 对象会为它们的描述和存储立即数保留一些内存。

Usually, only arrays and strings can have significant shallow sizes. However, strings often have their main storage in renderer memory, exposing only a small wrapper object on the JavaScript heap.

通常,只有数组和字符串可以具有显着的浅层大小。然而,字符串通常主要存储在渲染器内存中,只在 JavaScript 堆上暴露一个小的包装器对象。

Nevertheless, even a small object can hold a large amount of memory indirectly, by preventing other objects from being disposed by the automatic garbage collection process. The size of memory that will be freed, when the object itself is deleted, and its dependent objects made unreachable from GC roots, is called retained size.

尽管如此,通过防止其他对象被自动垃圾收集进程处理,即使是一个小对象也可以间接持有大量内存。当对象本身被删除,并且其依赖对象无法从 GC 根访问时,将被释放的内存大小称为保留大小。

Devtools Docs

开发工具文档

回答by Shomz

If you want to use properties once you instantiate the object, varwon't work, see below:

如果您想在实例化对象后使用属性,var将不起作用,请参见下文:

function MyObject() {
    var self = this;

    var a = 1;
    this.b = 2;

    var innerMethod = function() {

        logMessage(a); 
        logMessage(self.b); 
    }
}

var o = new MyObject();
console.log(o.a); // undefined
console.log(o.b); // 2