为什么我的javascript mixin不起作用?

时间:2013-10-02 05:09:00

标签: javascript mixins

看看这个klass实现(来自Alex MacCaw的Javascript Web Applications。),它为实例化对象添加了原型方法:

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;
};

adding instance properties位对我不起作用。

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');

问题是chow对象没有响应save方法。包含的回调然而有效。

我收到错误:Uncaught TypeError: Object #<Object> has no method 'save'

为什么?我该如何解决?

1 个答案:

答案 0 :(得分:3)

执行此行时:

Restaurant.prototype = {...};

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

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