gpt4 book ai didi

javascript - 如何使用具有多个子原型(prototype)对象的原型(prototype)嵌套对象和共享变量?

转载 作者:行者123 更新时间:2023-11-30 19:37:18 25 4
gpt4 key购买 nike

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

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);

最佳答案

您正在设置新函数而不是设置新原型(prototype),因此每个新函数的词法上下文与 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());

关于javascript - 如何使用具有多个子原型(prototype)对象的原型(prototype)嵌套对象和共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55800019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com