JavaScript closing features and anonymous functions

This code causes it to "!"register on the console.

var g = {};
(function() {
    var t = this;
    t.x = "x";
    g.a = function() {
        console.log(t.x);
    };
})();

(function() {
    var t = this;
    t.x = "!";
    g.b = function() {
        console.log(t.x);
    };
})();

g.a();

Share anonymous functions a this? Am I using it thisincorrectly? I really donโ€™t understand what is going on here.

I would like to g.a()keep returning the value xdefined in the first anonymous function.

I use node.js if that matters.

+5
source share
3 answers

this [docs]. , this , x .

, this, , .

  • funcName();, this .
  • , obj.funcName(), this .
  • new, new funcName();, this , .

this call [docs] apply [docs].


this :

var t = {};

: , node.js. . window, , node.js, , .

+4

- . , , :

var g = {};
(function() {
    var x = "x";
    g.a = function() {
        console.log(x);
    };
})();

(function() {
    var x = "!";
    g.b = function() {
        console.log(x);
    };
})();

g.a(); // "x"
g.b(); // "!"

g.a() g.b() x, x, . , , .

+3

script Chrome, , "this" "". , window.x, , window.x == "!" .

I donโ€™t understand what you expected from โ€œthisโ€ or what you are actually trying to accomplish with this code, so I donโ€™t know what alternative to offer. If you want the previous state in an anonymous function to be preserved for the internal function, you can simply rely on local variables (which will survive the closure) and not use the "this" link at all. The Squeegy example shows that.

+1
source

All Articles