javascript - 访问创建对象的范围内的 JavaScript 变量

标签 javascript scope this

当使用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/

相关文章:

javascript - 如何在新窗口中执行此操作?

c++ - 模板 + friend (致命组合)

scope - 带有 bool 变量 : If-Statement not working 的 SASS 混合

C++ 空值和 this 指针

javascript - 从同一类中的下拉列表 jquery 中获取值

javascript - 动态添加表行后 jquery 不工作

javascript - Jquery如何清理我自己的上传插件中的formData对象

Scala:导入如何防止找到隐式值?

javascript - 无法访问构造函数中的属性

javascript - 使用按钮 reactjs 映射列表时出现“此”问题