新的JS,有人可以帮助我理解为什么我不能检索这个值



我想知道为什么我不能检索警报函数中的值。我知道正在创建'mainObj',因为我可以在对象构造函数中使用警报进行测试。但我无法访问子对象属性。有人能解释一下我哪里做错了吗?下面是代码:

//used as a global
var theOBJ;
//child objects
function objChild(n,o,bgc){
    this.name = n;
    this.orientation = o;
    this.backgroundcolor = bgc;
}
//the Main Object
function objMain(n,o,bgc,ns){
    this.name = n;
    this.numsides = ns;
    if(this.numsides>2||this.numsides<1){
      alert("Number of sides are incorrect, setting to '1'"); 
      numsides=1;
    }
    child1 = new objChild(n+"_child1",o,bgc);
}

function createNewObject(n){
    //create a new Object
    theOBJ = new objMain(n,"landscape","",3);
    alert(theOBJ.child1.name);
}

因为您没有将child1对象分配给objMain构造函数中的this对象。由于它的定义不使用var,也不直接影响this,因此可能会污染全局范围。

应该是:

 function objMain(n,o,bgc,ns){
    this.name = n;
    this.numsides = ns;
    if(this.numsides>2||this.numsides<1){
      alert("Number of sides are incorrect, setting to '1'");
      // <<< this line also needs a change >>>
      this.numsides=1;
    }
    // <<< this line >>>
    this.child1 = new objChild(n+"_child1",o,bgc);
 }

最新更新