Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...