我有一个包含一系列对象的原型对象。其中一个数组对象被传递给一个函数,我需要访问它来自的原始对象...
有没有办法在不知道原始对象名称的情况下做到这一点?
示例:
function ObjectA {
this.attribute[0] = new ObjectB;
}
ObjectB.prototype.func = function (s) {
//I have the attribute[0] (an object) here, i need to access A
from it
}
var objectA = new ObjectA(data);
objectA.attribute[0].func(3);
答案 0 :(得分:1)
不,这是不可能的。您必须将ObjectA
或objectA
(不确定您想要的内容)传递给该函数。
这意味着函数必须接受该值作为参数:
ObjectB.prototype.func = function (s, target) {
// do whatever you want with `target`
}
你必须用
来调用它objectA.attribute[0].func(3, objectA);
但是,您也可以将对象的func
方法替换为另一个方法,该方法始终将ObjectA
传递给它:
function ObjectA {
const self = this;
const objB = new ObjectB;
objB.func = function(s) {
ObjectB.prototype.func.call(this, s, self);
};
this.attribute[0] = objB();
}
你可以继续调用函数
objectA.attribute[0].func(3);
您没有解释为什么要这样做,因此这些解决方案可能会或可能不会过于复杂或适合您的目标。
答案 1 :(得分:0)
原始问题的代码未显示正在设置的任何原型。如果我理解你正确的问题,你只是试图将一个对象的实例存储为另一个对象的属性。这就是你要找的东西:
// This is the not a prototype. It's just a regular constructor
// function that can be used to create instances of objects
function ObjectA(){
this.someProp = "test";
}
// This is the object that will gain access to the other's properties
function ObjectB() {
// You can't populate an array unless you have one first:
this.attribute = [];
// Now, you can populate it. But, you aren't utilizing prototypes
// with this code, you are just storing an instance of an object
// in an instance property of this one:
this.attribute[0] = new ObjectA();
}
// You need an instance to work with:
var B = new ObjectB();
// Now that new instance can get you properties of another object it
// is storing as a property:
console.log(B.attribute[0].someProp);

有关JavaScript中原型继承的工作原理的详细信息,请参阅 this other post of mine 来解释这一点。