在 Javascript 中使用 var 和 this 有什么区别?

发布于 2024-09-07 03:56:17 字数 111 浏览 8 评论 0原文

这些有什么区别呢?

var a = 13;  
this.b = 21;  
document.write(a);  
document.write(b);

What is the difference between these?

var a = 13;  
this.b = 21;  
document.write(a);  
document.write(b);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱花细雨 2024-09-14 03:56:17

对于全局代码(不属于任何函数的代码),它们几乎是等价的,两者最后都在全局对象上创建一个属性。

不同之处在于 a 已使用 var 语句声明,变量实例化过程将使用全局对象作为变量对象 (1),并且它将定义该属性不可删除,例如:

var a = 13;
delete a; // false
typeof a; // "number"

那么,b,因为全局代码中的this值指向全局对象本身,也将是一个全局属性,但这个可以删除:

this.b = 21;
delete b; // true
typeof b; // "undefined"

不要尝试 Firebug 中的第一个代码片段,因为 Firebug 的控制台使用 eval 在内部运行代码,并且在此执行上下文中变量实例化过程的行为有所不同,您可以此处尝试一下。

(1 ) 变量对象(VO)是变量实例化过程中使用的对象,用于定义 FunctionDeclarations 的标识符、使用 var 语句声明的标识符以及函数形参的标识符,在不同的执行上下文中,所有这些标识符都作为 VO 的属性进行绑定,作用域链由 VO 列表组成。

对于全局代码,VO 就是全局对象本身,这就是为什么 a 最终成为它的属性。对于函数代码,VO(也称为激活对象 for FunctionCode),是当您调用函数时在幕后创建的一个新对象,这就是创建新词法作用域的原因,总之我将讨论函数。

athis.b 都可以是 简单地通过ab解析,因为作用域链中的第一个对象又是全局对象。

另外,我认为了解变量实例化过程发生在代码执行之前是很重要的,例如:

alert(a); // undefined, it exists but has no value assigned to it yet
alert(b); // ReferenceError is thrown

var a = 13;
this.b = 21;

这些差异可能微不足道,但我认为值得了解它们。

现在,如果您发布的代码片段位于函数内,则它完全不同

在示例中使用 var 语句声明的 a 标识符将是一个局部变量,仅适用于函数的词法范围(并且任何嵌套函数)。

请记住,在 JavaScript 块中不会引入新的作用域,只有函数会引入新作用域,并且要在该作用域中声明变量,您应该始终使用 var

this.b 标识符将成为绑定到 this 值引用的对象的属性,但是...什么是 this???

JavaScript 中的 this 值是在调用函数时隐式设置的,它取决于您如何调用它:

  1. 当您使用 new 运算符时,<函数内的 code>this 值将指向新创建的对象,例如:

    函数测试() {
      this.foo = "酒吧";
    }
    var obj = new Test(); // 具有 `foo` 属性的新对象
    
  2. When您调用一个作为对象成员的函数,该函数内的this值将指向基对象,例如:

    var obj = {
      foo: 函数 () {
        返回 this == obj;
      }
    };
    obj.foo(); // 真的
    
  3. 当您调用没有任何基础对象的函数时,this 值将引用全局对象:

    函数测试() {
      返回这个==窗口;
    }
    测试(); // 真的
    
  4. this 值可以是当您使用 call 调用函数时显式设置应用

    函数测试() {
      警报(这个);
    }
    测试.call(“你好世界!”); // 警报“你好世界!”
    

For global code (code that is not part of any function), they are almost equivalent, both at the end create a property on the global object.

The difference is that a, which has been declared with the var statement, the Variable Instantiation process will use the global object as the Variable Object (1), and it will define that property as non-deleteable on it, e.g.:

var a = 13;
delete a; // false
typeof a; // "number"

Then, b since the this value in global code, points to the global object itself, will be also a global property, but this one can be deleted:

this.b = 21;
delete b; // true
typeof b; // "undefined"

Don't try the first snippet in Firebug, since the Firebug's console runs the code internally with eval, and in this execution context the variable instantiation process behaves differently, you can try it here.

(1) The Variable Object (VO) is an object that is used by the variable instantiation process to define the identifiers of FunctionDeclarations, identifiers declared with the var statements, and identifiers of function formal parameters, in the different execution contexts, all those identifiers are bound as properties of the VO, the Scope chain is formed of a list of VO's.

For global code, the VO is the global object itself, that's why a ends being a property of it. For function code, the VO (also known as the Activation Object for FunctionCode), is a new object is created behind the scenes when you invoke a function, and that is what creates a new lexical scope, in short I'll talk about functions.

Both a and this.b can be resolved simply as by a and b because the first object in the scope chain, is again the global object.

Also, I think is work knowing that the Variable Instantiation process takes place before than the code execution, for example:

alert(a); // undefined, it exists but has no value assigned to it yet
alert(b); // ReferenceError is thrown

var a = 13;
this.b = 21;

These differences may be trivial but I think is worth knowing them.

Now, if the code snippet you posted is within a function, it is completely different.

The a identifier, declared with the var statement in your example will be a local variable, available only to the lexical scope of the function (and any nested functions).

Keep in mind that in JavaScript blocks don't introduce a new scope, only functions do, and to declare a variable in that scope, you should always use var.

The this.b identifier will become a property bound to the object that is referred by the this value, but... What is this???.

The this value in JavaScript is implicitly set when you call a function, it is determined by how do you invoke it:

  1. When you use the new operator, the this value inside the function, will point to a newly created object, e.g.:

    function Test() {
      this.foo = "bar";
    }
    var obj = new Test(); // a new object with a `foo` property
    
  2. When you call a function that is member of an object, the this value inside that function will point to the base object, e.g.:

    var obj = {
      foo: function () {
        return this == obj;
      }
    };
    obj.foo(); // true
    
  3. When you invoke a function without any base object, the this value will refer to the global object:

    function test() {
      return this == window;
    }
    test(); // true
    
  4. The this value can be set explicitly, when you invoke a function using call or apply:

    function test() {
      alert(this);
    }
    test.call("hello world!"); // alerts "hello world!"
    
红颜悴 2024-09-14 03:56:17

简而言之,如果您在函数中使用它们,那么 -

this.a; //will create a public property

var b; //will create a member variable

例如,这里是 javascript 中的 Student 类

var Student = function()
{
    // Member variable
    var studentId;

    // Public property
    this.Name = "";
}

以了解更多信息 - 请参阅 使用 JavaScript 进行面向对象编程

To understand in short, if you use these in a function then -

this.a; //will create a public property

var b; //will create a member variable

e.g. here is a Student class in javascript

var Student = function()
{
    // Member variable
    var studentId;

    // Public property
    this.Name = "";
}

for more - See Object Oriented Programming with JavaScript

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文