当使用new
关键字创建对象时,除了传入调用上下文(this
)。
例如,如果我有:
var parent = function() {
this.parent_property = "Property set on parent object";
this.kid = new child();
};
var child = function() {
this.childMethod = function(){
//how to return parent property
}
};
var test = new parent();
console.log(test.kid.childMethod());
如何从 childMethod
访问 parent_property
?我能看到的唯一解决方案是将 this
传递给 child
的构造函数,如下所示:
var parent = function() {
this.parent_property = "Property set on parent object";
this.kid = new child(this);
};
var child = function(parent) {
var parent = parent;
this.childMethod = function(){
return parent.parent_property;
//how to return parent property
}
};
var test = new parent();
console.log(test.kid.childMethod());
还有其他方法可以做到这一点吗?这样做有什么缺点/陷阱吗?
最佳答案
在以下代码中,没有父级或子级:
var Child = function() {
this.childMethod = function(){
// how to return parent property
}
};
这只是一个构造函数,您可以从另一个构造函数调用它,但没有 inheritance到目前为止,还没有实例。
您当前的做法没有任何问题,但您可能对 prototypal inheritance 的理解不正确。在 JavaScript 中
这是来自 MDN 的示例
function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
};
Person.prototype.greeting = function() {
alert('Hi! I\'m ' + this.name.first + '.');
};
您将一个方法添加到 Person
构造函数的原型(prototype)中,以便 Person 的每个实例都将立即继承 greeting()
方法。
关于javascript - 访问创建对象的范围内的 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756765/