Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...