campari
campari

Reputation: 1005

Javascript: access to this inside prototype

I extend an object by using prototype. Using this inside nested functions does not refer to the object that is inherited but to the function itself.

The plugin i try to extend has an implementation of prototype already so there is a need to define a new object 'hungry':

var oSausage=function() {
    this.preference='hotdog';
}

oSausage.prototype.hungry={
    getPreference:function() {
        console.log(this.preference)
    },
    another:function() {

    },
    .....
}

Is there a way to refer to the object that is extended, i.e. oSausage?

Upvotes: 1

Views: 223

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

The core issue here is that the hungry object is independent of the oSausage one. Other objects can own a reference to it too. All oSausage has is a reference to it so your hugry object has no 'awareness' about its owner.

You can always keep a reference to it.

You can either do oSausage.hotdog directly, or do something like:

oSausage.prototype.hungry={
    sausage:oSausage,
    getPreference:function() {
        console.log(this.sausage.hotdog)
    },
    another:function() {

    },
    .....
}

Upvotes: 1

Related Questions