【问题标题】:Javascript object as parent for another js objectJavascript 对象作为另一个 js 对象的父对象
【发布时间】:2015-05-09 09:08:43
【问题描述】:

你能解释一下如何用 JavaScript 做这样的事情吗:

  1. 创建一个对象。
  2. 创建第二个对象。
  3. 将第一个对象设置为第二个对象的父对象。
  4. 将第二个对象作为子对象添加到第一个对象。

对于作为 Java 开发人员的我来说,这听起来很简单,但我现在很困惑。

演示:

var childFunction = function(parent){
    this.parent = parent;
    this.value = 14;
    this.fun = function(){
        document.getElementById("test").innerHTML=parent.value;
    };
    this.setParent = function(parent){
        this.parent = parent;
    }
}

var parentFunction = function(){
    this.value=20;
    this.child=''; 
    
    this.addChild = function(child){
        child.setParent(this);
        this.child=child; 
    }
    
    this.setchild = function(child){
        this.child = child;
    }
    this.createChild= function(){
        this.child = new childFunction(this);
    }
}


var par = new parentFunction();
var ch = new childFunction('');
//par.setchild(new childFunction(par));
//par.createChild();
par.addChild(ch);

par.child.fun();
<div id="test"></div>

【问题讨论】:

  • 检查this在每种情况下引用的内容,您可能会感到惊讶。
  • 代码似乎是正确的,你目前的问题是什么?

标签: javascript oop prototype


【解决方案1】:

只要您更改,它就可以在fiddle 开始工作:

 document.getElementById("test").innerHTML=this.parent.value;

【讨论】:

    【解决方案2】:

    当前代码没有在子构造函数中将父传递给子。

    正如@Axel 在他的回答中指出的那样,问题的原因是变量parent 没有绑定到任何东西,除非您在名为parent 的构造函数参数中传入父级。通过在子构造函数中传入parent,您可以为此行创建一个闭包:

    document.getElementById("test").innerHTML=parent.value;
    

    以下已修复:

    var childFunction = function(parent){
        this.parent = parent;
        this.value = 14;
        this.fun = function(){
            document.getElementById("test").innerHTML=parent.value;
        };
        this.setParent = function(parent){
            this.parent = parent;
        }
    }
    
    var parentFunction = function(){
        this.value=20;
        this.child=''; 
        
        this.addChild = function(child){
            child.setParent(this);
            this.child=child; 
        }
        
        this.setchild = function(child){
            this.child = child;
        }
        this.createChild= function(){
            this.child = new childFunction(this);
        }
    }
    
    
    var par = new parentFunction();
    var ch = new childFunction(par);  //<-- pass parent in child constructor
    
    par.addChild(ch);
    
    par.child.fun();
    &lt;div id="test"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2023-01-08
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2012-12-05
      • 2017-01-19
      相关资源
      最近更新 更多