【问题标题】:Using Prototype's Class.create to define private/protected properties and methods使用 Prototype 的 Class.create 定义私有/受保护的属性和方法
【发布时间】:2009-05-21 23:03:29
【问题描述】:

有一个很好的通用方法可以在 Javascript 中定义私有和受保护的属性和方法,here on the site。但是,当前版本的 Prototype (1.6.0) 没有通过其Class.create() 语法定义它们的内置方法。

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

【问题讨论】:

    标签: javascript oop prototypejs private protection


    【解决方案1】:

    Prototype 的灯塔中有一个讨论 here,它解释了为什么您无法使用 Prototype 的 Class.create 获得这种效果。

    【讨论】:

    • 您能给我访问此链接的权限吗?我同意你的意见,但我想看到讨论,但它需要登录。它不允许我使用我的 Google 登录...
    • Here 是由 archive.org 捕获的讨论链接。
    • 谢谢。这是一个非常有趣的讨论。我很想看到这个实现。我已经详细查看了补丁,它看起来非常可靠。我会用合并到prototype-1.7.3.js的补丁做一些测试,看看这是否可靠......
    【解决方案2】:

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

    这是一个代码示例:

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

    这是 Douglas Crockford 关于这个主题的理论。

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

    【讨论】:

    • 太棒了。谢谢。我也对 TML 的答案投了赞成票,因为他包含的链接对此主题进行了全面讨论,并揭示了为什么其他(看起来更干净)的实现不起作用。
    • @SleepyCod :您将如何定义一个完全封装的私有变量,即没有 setter 或 getter 的私有变量?您的示例有一个 getter,因此其他类方法可以获取该字段,但这会将该字段暴露给外界。
    • @Christophe Eblé 这不是私有方法。使用 var getProtectedMember = function(){... 但是,这样就无法从其他方法中访问此方法,但至少无法从类外部访问它。我正在研究是否有可能允许从内部而不是外部访问方法......
    【解决方案3】:

    关键是将公共方法添加为闭包,如下例所示:

     Bird = Class.create (Abstract,(function () {
        var string = "...and I have wings"; //private instance member
        var secret = function () {
            return string;
        } //private instance method
        return {
            initialize: function (name) {
                this.name = name;
            }, //constructor method
            say: function (message) {
                return this.name + " says: " + message + secret();
            } //public method
        }
    })());
    
    Owl = Class.create (Bird, {
        say: function ($super, message) {
            return $super(message) + "...tweet";
        } //public method
    })
    
    var bird = new Bird("Robin"); //instantiate
    console.log(bird.say("tweet")); //public method call
    
    var owl = new Owl("Barnie"); //instantiate
    console.log(owl.say("hoot")); //public method call inherit & add
    

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 2020-03-31
      • 2020-11-15
      • 2013-01-18
      • 2012-01-09
      • 2018-10-17
      • 1970-01-01
      • 2023-03-04
      • 2016-02-19
      相关资源
      最近更新 更多