【问题标题】:Accessing this variable from method instance从方法实例访问此变量
【发布时间】:2014-05-16 16:08:42
【问题描述】:

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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

    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-methods,Javascript - Is it a bad idea to use function constructors within closures?

    【讨论】:

    • @MrCode:谢谢,当然应该。如果您只是编辑帖子,我不会介意:-)
    • 我在调用 makeBag 方法后设置了 me.name = "Smo"。然后 myBag.getOwnerName() 返回 John。这就是我想要它做的,但为什么会发生这种情况?我的意思是,当传入的对象发生变化时,为什么this.owner会发生变化?
    • this.downer 属性没有改变,它仍然是(“指向”)me obj。但是那个对象已经变异了!
    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多