Asif Mallik
Asif Mallik

Reputation: 59

Accessing this variable from method instance

How do you access the this object from another object instance?

var containerObj = {
    Person: function(name){
        this.name = name;
    }
}
containerObj.Person.prototype.Bag = function(color){
    this.color = color;
}
containerObj.Person.prototype.Bag.getOwnerName(){
    return name; //I would like to access the name property of this instance of Person
}

var me = new Person("Asif");
var myBag = new me.Bag("black");
myBag.getOwnerName()// Want the method to return Asif

Upvotes: 1

Views: 65

Answers (1)

Bergi
Bergi

Reputation: 664548

Don't put the constructor on the prototype of another class. Use a factory pattern:

function Person(name) {
    this.name = name;
}
Person.prototype.makeBag = function(color) {
    return new Bag(color, this);
};

function Bag(color, owner) {
    this.color = color;
    this.owner = owner;
}
Bag.prototype.getOwnerName = function() {
    return this.owner.name;
};

var me = new Person("Asif");
var myBag = me.makeBag("black");
myBag.getOwnerName() // "Asif"

Related patterns to deal with this problem: Prototype for private sub-methods, Javascript - Is it a bad idea to use function constructors within closures?

Upvotes: 2

Related Questions