代码之家  ›  专栏  ›  技术社区  ›  David Cournapeau

javascript原型和闭包中的“this”访问

  •  5
  • David Cournapeau  · 技术社区  · 14 年前

    我是JS的初学者,对以下代码感到困惑:

    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();
    

    我被期望得到“current arg:bar”,但得到“current arg:undefined”。我注意到,首先将this.arg复制到一个“normal”变量中,并在闭包工程中引用该变量:

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

    我是在做错事,期望错误,还是属于JSWTF?

    2 回复  |  直到 14 年前
        1
  •  3
  •   bobobobo    14 年前

    new 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 ) ;
    

    function

        2
  •  4
  •   theazureshadow    14 年前

    this window

    call apply