gpt4 book ai didi

javascript - 从方法实例访问此变量

转载 作者:行者123 更新时间:2023-11-30 17:28:32 25 4
gpt4 key购买 nike

如何从另一个对象实例访问 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

最佳答案

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

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?

关于javascript - 从方法实例访问此变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23699904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com