2017-09-09 36 views
-1

我有一个原型对象,其中包含一个对象数组。其中一个数组对象被传递给一个函数,我需要访问它来自的原始对象...获取原始原型对象内给定一个变量存储在原始原型

有没有任何方法可以在不知道原始对象的名称的情况下做到这一点?

例子:

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

也许你需要编辑你的问题来改进代码部分? – Kalamarico

+0

你的问题不清楚 – marvel308

+0

你的问题的代码没有显示任何正在建立的原型。 –

回答

1

不,这是不可能的。你必须通过ObjectAobjectA(不知道你想要什么)的功能。

这意味着函数必须接受该值作为参数:

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); 

你没有解释为什么要做到这一点,因此这些解决方案可能是你正在尝试做的或可能不适合过于复杂或合适的。

+0

你张贴在这里的第二个解决方案我指出了正确的方向,我得到它的工作。非常感谢帮助,谢谢。 – timdirusso

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解释说。

+0

分配给ObjectB.prototype.func是设置原型,不是吗?我猜测OP只是省略了ObjectB的声明。 –

+0

我编辑了代码块。在这种情况下,会有另一个函数将B.attribute [0] .someProp作为参数。在同一个函数中,我需要访问B.我只能访问someProp – timdirusso

+0

@FelixKling原始文章不包含该代码。 –