使用 Prototype 的 Class.create 定义私有/受保护的属性和方法 [英] Using Prototype's Class.create to define private/protected properties and methods

查看:37
本文介绍了使用 Prototype 的 Class.create 定义私有/受保护的属性和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个很好的通用方法可以在 Javascript 中定义私有和受保护的属性和方法,这里在网站上.但是,当前版本的 Prototype (1.6.0) 没有内置的方法来通过其 Class.create() 语法.

There is a good generalized method for defining private and protected properties and methods in Javascript, here on the site. However, the current version of Prototype (1.6.0) doesn't have a built-in way to define them through its Class.create() syntax.

我很好奇开发人员在使用 Prototype 时想要定义私有和受保护的属性和方法时的最佳实践是什么.有没有比通用更好的方法?

I'm curious what the best practices are when developers want to define private and protected properties and methods when using Prototype. Is there a better way than the generic one?

推荐答案

你可以做的是在你的构造函数中使用局部变量(初始化)作为原型,然后创建一个闭包来访问/公开这个变量给你的公共方法.

What you can do is using local variables in your constructor function (initialize) for prototype and then creating a closure that will access/expose this variable to your public methods.

这是一个代码示例:

// properties are directly passed to `create` method
var Person = Class.create({
   initialize: function(name) {
      // Protected variables
      var _myProtectedMember = 'just a test';

      this.getProtectedMember = function() {
         return _myProtectedMember;
      }

      this.name = name;
   },
   say: function(message) {
      return this.name + ': ' + message + this.getProtectedMember();
   }
});

这是关于该主题的道格拉斯·克罗克福德理论.

Here's Douglas crockford theory on the subject.

http://www.crockford.com/javascript/private.html

这篇关于使用 Prototype 的 Class.create 定义私有/受保护的属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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