我如何做JavaScript原型继承(原型链)

Dan*_*sky 9 javascript inheritance prototype chain

这是JavaScript的大师的问题.我正在尝试使用JavaScript原型模型更优雅.这是我的实用程序代码(它提供了真实的原型链和使用instanceof运算符的正确工作):

function Class(conf) {
  var init = conf.init || function () {};
  delete conf.init;

  var parent = conf.parent || function () {};
  delete conf.parent;

  var F = function () {};
  F.prototype = parent.prototype;
  var f = new F();
  for (var fn in conf) f[fn] = conf[fn];
  init.prototype = f;

  return init;
};
Run Code Online (Sandbox Code Playgroud)

它允许我这样做:

var Class_1 = new Class({
  init: function (msg) { // constructor
    this.msg = msg;
  },

  method_1: function () {
    alert(this.msg + ' in Class_1::method_1');
  },

  method_2: function () {
    alert(this.msg + ' in Class_1::method_2');
  }
});

var Class_2 = new Class({
  parent: Class_1,

  init: function (msg) { // constructor
    this.msg = msg;
  },

  // method_1 will be taken from Class_1

  method_2: function () { // this method will overwrite the original one
    alert(this.msg + ' in Class_2::method_2');
  },

  method_3: function () { // just new method
    alert(this.msg + ' in Class_2::method_3');
  }
});

var c1 = new Class_1('msg');
c1.method_1(); // msg in Class_1::method_1
c1.method_2(); // msg in Class_1::method_2

var c2 = new Class_2('msg');
c2.method_1(); // msg in Class_1::method_1
c2.method_2(); // msg in Class_2::method_2
c2.method_3(); // msg in Class_2::method_3

alert('c1 < Class_1 - ' + (c1 instanceof Class_1 ? 'true' : 'false')); // true
alert('c1 < Class_2 - ' + (c1 instanceof Class_2 ? 'true' : 'false')); // false

alert('c2 < Class_1 - ' + (c2 instanceof Class_1 ? 'true' : 'false')); // true
alert('c2 < Class_2 - ' + (c2 instanceof Class_2 ? 'true' : 'false')); // true
Run Code Online (Sandbox Code Playgroud)

我的问题是:有更简单的方法吗?

Dan*_*sky 0

经过一些研究后,我得出结论,没有更简单的方法可以做到这一点。