Javascript中继承建模的优缺点?

Chr*_*ris 9 javascript oop inheritance prototype-programming

我意识到Javascript没有类,并且没有构建为具有经典的OOP继承.但是我发现这样的模式非常有用,我想构建一种简单的方法来模拟这种行为,理想的是利用Javascript灵活性的最佳部分.以下方法的优缺点是什么?

我的自定义库中有以下功能:

function inherit(superClass, args, instance) {
    var subClass = inherit.caller;
    var o = new superClass(args);
    for(p in o) {
        if(o.hasOwnProperty(p)) init(instance, p, o[p]);
        else init(subClass.prototype, p, o[p]);
    }
}

function isUndefined(x) {var u; return x === u;}

// sets p to value only if o[p] is undefined
function init(o, p, value) {if(isUndefined(o[p])) o[p] = value;}
Run Code Online (Sandbox Code Playgroud)

此设置需要两个约定:

  1. 建模类的函数必须使用一个参数:具有命名属性的对象
  2. 希望从另一个"继承"的函数必须调用inherit函数.

以下是您获得的结果的示例(粘贴到Firebug命令行以及库函数,以查看它的运行情况):

function SuperClass(args) {
  this.x = args.x;
}

SuperClass.prototype.p = 'SuperClass prototype property p';

function SubClass(args) {
  inherit(SuperClass, args, this);
  this.y = args.y;
}

SubClass.prototype.q = 'SubClass prototype property q';

var o = new SubClass({
  x: 'x set in SuperClass',
  y: 'y set in SubClass'
});

console.dir(o);  // correctly has properties x, y, p, and q

['x', 'y', 'p', 'q'].forEach(function(prop) {
  // true for x and y, false for p and q
  console.log("o.hasOwnProperty('" + prop + "')", o.hasOwnProperty(prop));
});

console.log("o instanceof SubClass: ", o instanceof SubClass);      // true
console.log("o instanceof SuperClass: ", o instanceof SuperClass);  // false
Run Code Online (Sandbox Code Playgroud)

我知道以下缺点:

  1. 修改超类原型不会影响您的实例对象,正如您对原型样式继承所期望的那样
  2. 实例对象不会注册为超类的实例(虽然它仍然会像一个一样嘎嘎叫)
  3. 参数约定可能很烦人

和专业人士:

  1. 只需要一个函数调用(易于实现)
  2. 区分原型属性和实例属性
  3. 传递给子类的参数也传递给超类
  4. 由超类构造函数设置的实例属性可立即在子类构造函数中使用
  5. 多继承很简单,只需在子类中多次调用inherit
  6. 不会覆盖子类的现有属性

优点3 - 6特别使这种方法对我来说比方法更有用SubClass.prototype = new SuperClass().其他方法,如dojo的类建模,要复杂得多,我认为是不必要的.

那么,告诉我你的想法.如果其他人之前已经这样做了,请告诉我,我不打算复制任何想法.

bre*_*dan 3

您可能想看看 John Resig 对 JavaScript 继承做了什么: http://ejohn.org/blog/simple-javascript-inheritance/

这是我所见过的 Javascript 继承的最佳尝试。