“var”变量,“this”变量和“全局”变量 - JavaScript构造函数内部 [英] “var” variables, "this" variables and "global" variables - inside a JavaScript Constructor

查看:165
本文介绍了“var”变量,“this”变量和“全局”变量 - JavaScript构造函数内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我最后一个问题之后,这一个对我来说更准确:

After my last question, this one is more accurate for me:

例如:

function Foo() {
    this.bla = 1;
    var blabla = 10;
    blablabla = 100;
    this.getblabla = function () { 
        return blabla; // exposes blabla outside
    }
}
foo = new Foo();

我现在理解:

this.bla = 1;     // will become an attribute of every instance of FOO.
var blabla = 10;  // will become a local variable of Foo(will **not** become an attribute of every instance of FOO), which could be accessed by any instance of FOO - only if there's a method like "this.getBlabla". that's a "closer" ?
blablabla = 100;  // will define a **new** (or change if exist) global(window) variable.

我理解是否正确?

- 如果我包括在承包商中使用它的 var blabla = 10; getblabla 函数, of Foo(foo...),将在包含此private变量的内存中保存一个Foo contractor函数。或者是与Foo的 ALL 实例(例如foo)的私有变量的位置相同的Foo函数?

Also - if I include var blabla = 10; and the getblabla function that uses it in the contractor, then for every instance of Foo("foo"...), there will be saved a Foo contractor function in the memory that includes this "private" variable. or will it be the same Foo function as place for the private variables - for ALL instances(like "foo") of Foo?

推荐答案

仅仅关注范围,我将通过这个例子(使用更清晰的变量)。然后,我将它连接到你的变量。

Just to focus on the scope, I'm going to run through this example, (with clearer variables) Afterwards, I'll connect it back to your variables.

var x = "Global scope";
var y = "Not changed.";

function Foo() {
    this.x = "Attribute of foo";
    var x = "In foo's closure";
    y = "Changed!"
    this.getX = function () { 
        return x;
    }
}

// do some logging

console.log(x); // "Global scope"
console.log(y); // "Not changed"
foo = new Foo();
console.log(y); // "Changed!"
console.log(foo.x); // "Attribute of foo"
console.log(x); // "Global scope"
console.log(foo.getX()); // "In foo's closure"

行: this.x 等价于 this.bla ,它定义了一个 Foo 对象的外部可用属性。 y 等效于 blablabla = 100 ,然后 x 在foo中相当于你的 blablabla 在foo中。这是一个非常粗糙的 jsfiddle ,你可以运行去看这个。

The line: this.x is equivalent to this.bla, and it defines an externally available attribute of a Foo object. y is equivalent to blablabla=100 and then the x within foo is equivalent to your blablabla within foo. Here's a really rough jsfiddle you can run to see this.

这篇关于“var”变量,“this”变量和“全局”变量 - JavaScript构造函数内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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