Jacket fan
Jacket fan

Reputation: 3

javascript prototype object this value

I don't really get JavaScript prototyping. In the following example why is the output of tmp.foo.tt() undefined, and how do you define it?

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

Upvotes: 0

Views: 65

Answers (1)

nils
nils

Reputation: 27204

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

Upvotes: 1

Related Questions