繁体   English   中英

javascript原型对象此值

[英]javascript prototype object this value

我真的没有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

您可以使用吸气剂解决此问题,尽管您将失去原型通常提供的一些优势:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM