Using Prototype's Class.create to define priva

2019-07-23 03:27发布

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.

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?

3条回答
forever°为你锁心
2楼-- · 2019-07-23 04:02

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.

Here's a code example:

// 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

查看更多
Lonely孤独者°
3楼-- · 2019-07-23 04:03

There's a discussion here in Prototype's lighthouse that shows that explains why you can't get this effect with Prototype's Class.create.

查看更多
女痞
4楼-- · 2019-07-23 04:12

The key is to add the public methods as closures, as in the example below:

 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
查看更多
登录 后发表回答