I am trying to access a variable in A from B (in my example bellow). I didn't extend B from A, because A is just a container.
function A() {
var Parent = this;
this.container = [];
}
A.prototype.add = function(Item) {
Parent.container.push(Item);
}
function B() {
}
B.prototype.exec = function() {
console.log(Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B();
Manager.add(B);
Item.exec();
How to access Parent
from Item
?
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
this.container.push(Item);
}
function B(Parent) {
this.Parent = Parent;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0]) //Uncaught ReferenceError: Parent is not defined
}
var Manager = new A();
var Item = new B(Manager);
A.add(B);
B.exec();
function A() {
this.container = [];
}
A.prototype.add = function(Item) {
//assigning parent property only if Item is added
Item.Parent = this;
this.container.push(Item);
}
function B() {
this.Parent = null;
}
B.prototype.exec = function() {
console.log(this.Parent.container[0])
}
var Manager = new A();
var Item = new B();
Manager.add(Item);
Item.exec();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.