从方法实例访问此变量

时间:2014-05-16 16:08:43

标签: javascript

如何从另一个对象实例访问此对象?

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

1 个答案:

答案 0 :(得分:2)

不要将构造函数放在另一个类的原型上。使用工厂模式:

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"

处理此问题的相关模式:Prototype for private sub-methodsJavascript - Is it a bad idea to use function constructors within closures?