Javascript 继承似乎无处不在。堪称“Javascript 语言奇案”。
这个想法是有一个基类,然后你扩展基类以获得类似继承的功能(不完全,但仍然如此)。
整个想法是获得原型的真正含义。直到我看到 John Resig 的代码(接近于 jQuery.extend 所做的)编写了一个代码块,他声称 base2 和原型库是灵感的源泉,我才明白这一点。
这里是代码。
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
有三个部分在做这项工作。首先,循环遍历属性并将它们添加到实例中。之后,您创建一个构造函数,以便稍后添加到对象中。现在,关键行是:
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
您首先将Class.prototype 指向所需的原型。现在,整个对象都发生了变化,这意味着您需要强制将布局恢复为自己的布局。
以及用法示例:
var Car = Class.Extend({
setColor: function(clr){
color = clr;
}
});
var volvo = Car.Extend({
getColor: function () {
return color;
}
});
在Javascript Inheritance by John Resig 的帖子中了解更多信息。