JavaScript模块模式 - 受保护的成员?

bre*_*ung 8 javascript inheritance

喂!这是我的第一个问题!

我正在尝试Doug Crockford和其他人推广的模块模式.到目前为止,它对它非常满意,但我对处理某种继承模式的最佳方法有点不确定.

我把它归结为使用猫和哺乳动物的裸骨盒,尽管我的目的是为帆布制作基于瓷砖的游戏的对象.

但这是我使用浏览器警报的裸骨'动物'案例:

var ZOO = ZOO || {};
//
ZOO.mammal = function () {
   "use strict";
   var voice = "squeak.mp3", // default mammal sound
      utter = function () {
         window.alert(this.voice);
      };
//
   // public interface
   return {
      utter: utter,
      voice: voice
   };
};
//
ZOO.cat = function () {
   "use strict";
   // hook up ancestor
   var thisCat = ZOO.mammal();
   thisCat.voice = "miaw.mp3";
   return thisCat;
};
//
var felix = ZOO.cat();
felix.utter();
Run Code Online (Sandbox Code Playgroud)

让我对这种方法感到困扰的是,我必须创建voice一个公共财产,以便猫可以修改它.

我真正想要的是"受保护"的可见性(来自Java,ActionScript等),因此cat可以在voice没有任何人felix能够修改它的情况下进行修改.

有解决方案吗?

Ada*_*kis 14

您可以通过将空白对象传递到基础"类"来充当受保护属性的存储库,从而模拟受保护的可见性(对您自己和子对象可见).这将允许您通过继承链共享属性,而不会将其公开.

var ZOO = ZOO || {};

ZOO.mammal = function (protectedInfo) {
   "use strict";
   protectedInfo = protectedInfo || {};
   protectedInfo.voice = "squeak.mp3";

   // public interface
   return {
      utter: function () {
         alert(protectedInfo.voice);
      }
   };
};

ZOO.cat = function () {
   "use strict";

   var protectedInfo = {};
   // hook up ancestor
   var thisCat = ZOO.mammal(protectedInfo);

   protectedInfo.voice = "miaw.mp3";
   return thisCat;
};
Run Code Online (Sandbox Code Playgroud)

这是一个现场演示