素人がプログラミングを勉強していたブログ

プログラミング、セキュリティ、英語、Webなどのブログ since 2008

連絡先: すかいぷ:javascripter_  か javascripter あっと tsukkun.net skypeのほうがいいです

プライベートなメンバ

function createClass(base){
  var self = {};
  function Class()
    self.initialize.apply(self, arguments);
  for(var key in base) if(base.hasOwnProperty(key)){
    extend(base, key, self, self);
    if(key.charAt(0) != "_"){
      extend(base, key, Class.prototype, self);
    }
  }
  return Class;
  function extend(base, name, target, self){
    var setter = base.__lookupSetter__(name);
    var getter = base.__lookupGetter__(name);
    var trigger = 1;
    if(setter){
      trigger &= 0;
      target.__defineSetter__(name, setter.bind(self));
    }
    if(getter){
      trigger &= 0;
      target.__defineGetter__(name, getter.bind(self));
    }
    if(trigger){
      if(typeof base[name] == "function")
        target[name] = base[key].bind(self);
      else
        target[name] = base[name];
    }
  }
}
Function.prototype.bind = function bind(thisObj) {
  var self = this,
  args = Array.slice(arguments, 1);
  return function() {
    Array.prototype.unshift.apply(arguments, args);
    return self.apply(thisObj, arguments);
  }
};

var Counter = createClass({
  _counter: null,
  initialize: function(defaultValue){
    this._counter = defaultValue || 0;
  },
  get counter counter()
    this._counter,
  set counter counter(value){
    if(typeof value != "number" && !(value instanceof Number))
      throw "The counter should be a number";
    return this._counter = value;
  },
  increment: function increment()
    ++this._counter,
  show:function show(){
    console.log(this._counter);
  }
});

var counter = new Counter(0);
console.log("_counter in counter:", "_counter" in counter); // false
counter.show(); // 0
counter.increment();
counter.show(); // 1
counter.counter = 5;
console.log("counter:", counter.counter); // 5
counter.counter = "bad arg"; // throw "The counter should be a number"