使用“var” JavaScript构造函数中的变量? [英] What happens with "var" variables inside a JavaScript Constructor?

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

问题描述

example:

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

foo = new Foo();

原始问题

我知道bla将被分配给Foo的每个实例。
blabla会发生什么?

I know that bla will be assigned to every instance of Foo. What will happen with blabla?

新问题:

我现在理解:

this.bla = 1;     // will become an attribute of every instance of FOO.
var blabla = 10;  // will become a local variable of Foo(**not** 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".
blablabla = 100;  // will define a **new** (or change if exist) global(window) variable.

                     Did i understand correctly?


推荐答案

c> this - ie: this.method = function(){}; / strong>您的Foo构造函数, 全部 将引用 blahblah 每个实例的 Foo 对象。

Any internal-methods you give to this -- ie: this.method = function () {}; while inside of your Foo constructor function, are all going to have a reference to the blahblah which is unique to each instance of a Foo object.

function Wallet () {
    var balance = 0;
    this.checkBalance = function () { return balance; };
    this.depositAmount = function (amount) { balance += amount; };
}


var wallet = new Wallet();
wallet.checkBalance();   // 0
wallet.depositAmount(3);
wallet.checkBalance();   // 3

但是它完全受到保护,不能在钱包外面访问,除非你将它返回给某人,从特权功能。

But it's completely protected from access outside of wallet, unless you return it to somebody, from a privileged function.

wallet.balance; // undefined;

(添加的兴趣位 - 如果 balance 字符串数字布尔 ,即使您返回它,也不会给予人们编辑权限,甚至永久查看访问权限 - 标量变量是通过值传递的,因此您只是传递balance 的值 - 如果平衡是对象函数数组,他们有永久访问权限修改内部工作流程)

(added bit of interest -- if balance is a string, a number, or a boolean, even if you return it, that won't give people editing rights, or even permanent viewing access -- scalar variables are passed by value, so you're just passing the value of balance at the time -- if, however, balance was an object, a function or an array, they'd have permanent access to modify the crap out of your internal workings)

注意:方法 HAVE 可以在构造函数中分配,以使其工作。
原型无法访问内部变量。
稍后添加方法不会给他们访问内部变量。

Note: methods HAVE to be assigned inside of the constructor for this to work. Prototypes can't access internal variables. Adding methods later won't give them access to internal variables.

这意味着每个实例将占用更多的内存,因为每个实例都有自己的方法的副本,并有自己的vars副本。
但是如果你在做什么需要私人数据,这将是一个很好的方法来获得它。

This means that each instance will take up a little more memory, because each has its own copy of the methods, and has its own copy of the vars. But if what you're doing requires private data, this would be a good way to get it.

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

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