Javascript prototype and "this" access in close

I start in js and am puzzled by the following code:

Foo = function(arg) {
    this.arg = arg;
};

Foo.prototype = {
    init: function () {
        var f = function () {
            alert("current arg: " + this.arg); // am expecting "bar", got undefined
        }
        f();
    }
};

var yo = Foo("bar");
yo.init();

I expected to get "current arg: bar", but got "current arg: undefined". I noticed that by first copying this.arg into a “normal” variable, and referring to this variable in the closure, do:

Foo.prototype = {
    init: function () {
        var yo = this.arg;
        var f = function () {
            alert("current arg: " + yo);            }
        f();
    }
};

Am I doing something wrong, am I mistaken, or is he getting into one of the js WTF?

+5
source share
2 answers

It depends on how the function was called.

If called with a keyword new, it thisrefers to the object that is being created (which will be implicitly returned at the end of the function).

, this window.

:

// Constructor for Foo,
// (invoke with keyword new!)
function Foo()
{
  this.name = "Foo" ;
}

myFoo = new Foo() ;
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ; // window.name will be empty

// now if we invoke Foo() WITHOUT keyword NEW
// then all references to `this` inside the
// function Foo will be to the
// __global window object__, i.e. the global window
// object will get clobbered with new properties it shouldn't
// have! (.name!)

Foo() ;  // incorrect invokation style!
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ;

JavaScript "" , , JavaScript , function "" - invokation ( , new , )

+3

this window. - , .

( call apply .)

+4

All Articles