继承主要有3种javascript,根据书Javascript 的优点: 伪古典, 原型 and 功能性.
您刚刚发布的内容将位于伪古典继承,您可以使用构造函数模拟类行为。
我发现更有用和灵活功能性模式,它允许您保护变量(使它们私有)。
var constructor = function (spec, my) {
var that, other private instance variables;
my = my || {};
//Add shared variables and functions to my
that = a new object;
//Add privileged methods to that
return that;
}
原型基本上是让您的对象直接从其他有用的对象继承,这就像将它们(有用的对象)作为您的新对象构造函数原型。
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
var a = {}
//Add shared variables to a
var b = Object.beget(a);
//Add new methods to b
例如,克罗克福德在他的书中说,每种模式都有很多考虑因素“函数式模式具有很大的灵活性。它比伪经典模式需要更少的努力,
并为我们提供更好的封装和信息隐藏以及对超级方法的访问。”,但我也看到过一些相反的文章,比如这个http://bolinfest.com/javascript/inheritance.php http://bolinfest.com/javascript/inheritance.php
编辑 - - -
如果您可能想了解实现超级方法的不同方法,请在功能性模式,您可以执行以下操作:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Object.method('superior', function (name) {
var that = this,
method = that[name];
return function ( ) {
return method.apply(that, arguments);
};
});
var archer = function (spec, accuracy) {
var that = warrior(spec),
super_displayInfo = that.superior('displayInfo');
that.getAccuracy = function() {
return accuracy;
};
that.setAccuracy = function(value) {
accuracy = value;
};
that.displayInfo = function (n) {
var form = super_displayInfo()
form.accuracy = that.getAccuracy();
return form;
};
return that;
};