簡體   English   中英

如何使用具有多個子原型對象的原型嵌套對象和共享變量?

[英]How do nest objects and share variables using prototype having multiple sub-prototype objects?

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

您正在設置新函數而不是設置新原型,因此每個新函數的詞法上下文與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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM