0

I am a newbie programmer and use namespace in Javascript.

There are something weird when programming . I have two "this" inside my namespace object , BUT there are two different results. One is represent Window Object , and the other is the namespace Object itself.

var namespace = {
    A : function A(){},
    B : function B(){
        var b = function b(){
       // "this" => Window Object
            console.log(this);
        };
        b();
      // "this" => namespace Object
        console.log(this);
    }
 }
 namespace.B();

I hope all this can represent the namespace Object. Is there something magic i can do?

Btw , I learned underscorejs library before. Is there any methods I can solve the problem with underscore library or merely pure javascript?

Thanks a lot.

Jay Chung
  • 99
  • 8
  • 2
    Within a function, `this` is set depending on how that function was called. Have a look at [MDN's `this` article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) for more information. A function's `this` value and the function's *scope* are two unrelated things. – nnnnnn Aug 22 '15 at 01:46
  • See http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440#3127440 – Jaromanda X Aug 22 '15 at 01:47
  • Good information !! I'll read it carefully – Jay Chung Aug 22 '15 at 02:34

1 Answers1

0

ECBO - execution context binding object. The context (this) is set from the calling object, i.e. the namespace before the dot. Since you've just used b(), then the ECBO is set to window. You could do b.call(namespace) which sets the context to an object of your choosing.

var namespace = {
    A : function A(){},
    B : function B(){
        var b = function b(){
            console.log(this); // "this" => namespace Object
        };
        b.call(namespace);
        console.log(this); // "this" => namespace Object
    }
 }
 namespace.B();
Data
  • 1,217
  • 10
  • 16