我的Javascript的O-O实现
function _class(cls) {
var result = function () {
!this.hasOwnProperty('upper') && (this.upper = function () {
return result.prototype;
});
cls.apply(this, arguments);
};
result.inherit = function (_super) {
// _super must be made by _class
this.prototype = new _super();
return this;
};
return result;
}
用法
var Person = _class(function () {
this.age = 1;
this.name = 'foo bar';
this.bucket = {
v1: 2,
};
var _methods = {
sayHi: function (msg) {
console.log(this.name + ': ' + msg);
}
};
$.extend(this, _methods);
});
var Soldier = _class(function () {
this.upper().constructor.apply(this, arguments);
var _methods = {
sayHi: function (msg) {
this.upper().sayHi(msg + ' from soldier');
}
};
$.extend(this, _methods);
});
Soldier.inherit(Person);
如果有兴趣可以参考另外2个实现
2008年John Resig的http://ejohn.org/blog/simple-javascript-inheritance/
Douglas Crockford的http://javascript.crockford.com/inheritance.html