如何使用具有多个子原型对象的原型嵌套对象并共享变量?

时间:2019-04-22 19:29:17

标签: javascript

我是JavaScript的新手,我试图了解继承的工作原理,我以前使用过C ++,并且很容易处理从主类到其后代的变量,我尝试了原型方法,但工作起来并不那么容易。 这是我的代码...什么是正确的方法?

function main() {
  this.name = "main object, name";

}
main.prototype.LevelA1 = function() {
  return "LevelA1 method " + this.name; //this level read this.name right
}
main.prototype.LevelA = function() {
  this.a = "laaaa"
  return "LevelA " + this.name; //variable this.name is visible

}

main.prototype.LevelA.LevelB = function() {

  return this.name + " Level B " + this.a //this.name undefined
}
main.prototype.LevelA.LevelB.LevelC = function() {
  return "level C" + this.name; //this.name not visible and not produce error
}
main.prototype.LevelA.LevelB.LevelC.LevelD = function() {
  this.bb = "variable of levelD"
  return "Level D " + this.bb + this.name; //this.name not visible and ot produce error

}
m = new main();
console.log(m.LevelA());
console.log(m.LevelA.LevelB());
console.log(m.LevelA.LevelB.LevelC());
console.log(m.LevelA.LevelB.LevelC.LevelD());
var cc = new m.LevelA.LevelB.LevelC.LevelD();
console.log(cc.bb);

1 个答案:

答案 0 :(得分:1)

您要设置新功能而不是设置新原型,因此每个新功能的词法上下文与Main.prototype无关。

我建议您使用类来学习逻辑。

此方法将“ Level”功能包装在从Main类扩展的类中。

class Main {
  constructor() {
    this.name = "main object, name";
  }
}

class MainLevel extends Main {
  LevelA1() {
    return "LevelA1 method " + this.name; //this level read this.name right  
  }

  LevelA() {
    this.a = "laaaa"
    return "LevelA " + this.name; //variable this.name is visible
  }

  LevelB() {
    return this.name + " Level B " + this.a //this.name undefined
  }

  LevelC() {
    return "level C" + this.name; //this.name not visible and not produce error
  }

  LevelD() {
    this.bb = "variable of levelD"
    return "Level D " + this.bb + this.name; //this.name not visible and ot produce error

  }
}

let m = new MainLevel();
console.log(m.LevelA());
console.log(m.LevelB());
console.log(m.LevelC());
console.log(m.LevelD());