代码之家  ›  专栏  ›  技术社区  ›  Jacket fan

javascript原型对象此值

  •  0
  • Jacket fan  · 技术社区  · 9 年前

    我并没有真正得到JavaScript原型。在下面的示例中,为什么tmp.foo的输出是。tt()未定义,如何定义?

    function Test(){
        this.name = 'test'
    }
    Test.prototype.foo = {
        tt: function(){
            console.log(this.name)
        }
    } 
    
    var tmp = new Test();
    tmp.foo.tt()    //why the output is undefined, and how to change it
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   nils    9 年前

    您可以使用getter来解决这个问题,尽管您会失去原型通常提供的一些优势:

    function Test(){
        this.name = 'test'
    }
    Object.defineProperty(Test.prototype, 'foo', {
        get: function() {
            var that = this;
            // that is now this
            return {
                tt: function(){
                    console.log(that.name);
                }
            }
        },
        configurable: true,
        enumerable: true
    });
    
    var tmp = new Test();
    tmp.foo.tt();