JavaScript模块模式 - 受保护的成员? [英] JavaScript Module Pattern - Protected members?

查看:75
本文介绍了JavaScript模块模式 - 受保护的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hullo! This is my first question!

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

I am experimenting with the module pattern promoted by Doug Crockford and others. Mostly very happy with it so far, but I am a little unsure about the best way of handling a certain inheritance pattern.

我把它归结为一个简单的骨头案例使用猫和哺乳动物,虽然我的目的是为帆布制作基于瓷砖的游戏的对象。

I have it boiled down to a bare bones case using cat and mammal, although my actual intention is to make objects for a tile based game in canvas.

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

But here is my bare bones 'animals' case using a browser alert:

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

这种方法令我烦恼的是我不得不做 voice 一个公共属性,以便cat可以修改它。

What bothers me about this approach is that I have had to make voice a public property so that cat can modify it.

我真正想要的是受保护的可见性(来自Java,ActionScript等) ,这样 cat 可以修改语音,而无法有权访问 felix 能够修改它。

What I really want is something like 'protected' visibility (from Java, ActionScript etc.), so that cat can modify voice without anyone with access to felix being able to modify it.

有解决方案吗?

推荐答案

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

You can simulate protected visibility (visible to yourself, and child objects) by passing a blank object to your base "class" to serve as the repository for your protected properties. This will allow you to share properties through your inheritance chain, without making them public.

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

这是现场演示

这篇关于JavaScript模块模式 - 受保护的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆