javascript var vs this [英] javascript var vs this

查看:63
本文介绍了javascript var vs this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

function MyObject() {
    var self = this;

    var a = 1;
    this.b = 2;

    var innerMethod = function() {

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

据我所知,只要MyObject,var就能存活生活,所以这和使用它一样吗?

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

编辑:

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

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

推荐答案

var a 您无法访问范围之外的变量,但是当您创建对象时可以使用分配此

with var a you cant access the variable outside the scope however assigning with this can be accessed when you make an object

当我们希望属性与对象的生命周期一起存在时,我们将属性添加到这个。我们将var用于局部变量。

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


我只对从对象内部访问变量感兴趣,
不是来自外部。

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

对于此语句的回答是使用 var 如果您只想在函数内部使用,那么因为var定义的变量只能访问代码声明它们的范围,或者在词汇嵌套范围内。

Answer to this statement is use var if 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.

所以Shomz建议你可以将其检查为:

so as Shomz suggested you can check it as:

var o = new MyObject();

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

a will be undefined as it is defined with var

  o.a; // undefined

而b将返回2,因为它在

while b will be return 2 as it is on this

 o.b; // 2

这篇关于javascript var vs this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆