简体   繁体   English

javascript原型对象此值

[英]javascript prototype object this value

I don't really get JavaScript prototyping. 我真的没有JavaScript原型。 In the following example why is the output of tmp.foo.tt() undefined, and how do you define it? 在下面的示例中,为什么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

You could work around this using a getter, although you will lose some of the advantages that prototypes generally provide: 您可以使用吸气剂解决此问题,尽管您将失去原型通常提供的一些优势:

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