开发者

JS: Difference in effect of how private functions are declared

开发者 https://www.devze.com 2023-03-04 21:12 出处:网络
In this JS snippet, I have an object with two versions of a private function (bar and bar2). I declare two instances, but I was caught out by the fact that one version of the private function (bar) se

In this JS snippet, I have an object with two versions of a private function (bar and bar2). I declare two instances, but I was caught out by the fact that one version of the private function (bar) seems to be wrongly accessing the value of the priva开发者_高级运维te var v in the OTHER object. Can anybody please tell me why this is?

Eric = function(_v)
{
    var v = _v;

    bar = function() {
        alert(v);
    };

    function bar2() {
        alert(v);
    };

    this.foo = function() {
        bar();
    };

    this.foo2 = function() {
        bar2();
    };
};

var e = new Eric('I am Eric');
var e2 = new Eric('I am Eric II');

e2.foo();   // outputs "I am Eric II"
e.foo();    // outputs "I am Eric II" ------ WHY?

e2.foo2();  // outputs "I am Eric II"
e.foo2();   // outputs "I am Eric"

Many thanks Andrew


bar = function() {
    alert(v);
};

You've made bar global. This means that bar is the second bar function defined in your call e2 = new Eric("I am Eric II");

Fix this by using var bar = ... to make it local.

As a seperate note you forgot var Eric.

You also do not need to locally declare var v since you the constructor argument _v is in scope. You can just continue using that argument instead.


It's because bar is being redefined on the object with the second call. If you switched to this it should work:

this.bar = function() {}

Of course, that breaks the private function you want. bar is not a symbol local to just your Eric instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消