Accessing this variable from method instance

后端 未结 1 1592
耶瑟儿~
耶瑟儿~ 2020-12-12 05:16

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

var containerObj = {
    Person: function(name){
        this.name = name;
    }
}
containerO         


        
相关标签:
1条回答
  • 2020-12-12 05:27

    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?

    0 讨论(0)
提交回复
热议问题