1

Take a look at this klass implementation (from Javascript Web Applications by Alex MacCaw.) that adds prototype methods for instantiated objects:

var Class = function(){
  var klass = function(){
    this.init.apply(this, arguments);
  };

  klass.prototype.init  = function(){};

  // Shortcut to access prototype
  klass.fn = klass.prototype;

  // Shortcut to access class
  klass.fn.parent = klass;

  // Adding class properties
  klass.extend = function(obj){
    var extended = obj.extended;
    for(var i in obj){
      klass[i] = obj[i];
    }
    if (extended) extended(klass)
  };

  // Adding instance properties
  klass.include = function(obj){
    var included = obj.included;
    for(var i in obj){
      klass.fn[i] = obj[i];
    }
    if (included) included(klass)
  };

  return klass;
};

The adding instance properties bit does not work for me.

var Restaurant = new Class;

Restaurant.prototype = {
  init: function(name, cuisine, location) {
    this.name = name || 'needs a name';
    this.cuisine = cuisine || 'needs a cuisine';
    this.location = location || 'needs a location';
  }
}

Restaurant.include({
  save: function(id) {  
    return 'saved';
  },
  destroy: function(id) { /* ... */ },
  included: function(klass) {
    console.log(klass, " was included!");
  }
});

var chow = new Restaurant('Chows', 'chinese', 'mumbai');

The problem is the chow object does not respond to the save method. The included callback however works.

I get the error: Uncaught TypeError: Object #<Object> has no method 'save'

Why is that? How do I fix it?

4

1 回答 1

3

当您执行此行时:

Restaurant.prototype = {...};

您刚刚替换了 Restaurant 对象的整个原型,因此它不再具有应该从klass. .include()例如,它不会有no .include(),该方法无法添加您的.save(),因此没有.save()

klass我假设你从书中得到的这段代码的工作方式,你没有分配给.prototype(因为那会破坏应该在那里的东西)。您要么调用.include()向原型添加新方法,要么.extend()向实例添加新方法。

于 2013-10-02T05:18:17.143 回答