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)
此设置需要两个约定:
以下是您获得的结果的示例(粘贴到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)
我知道以下缺点:
和专业人士:
优点3 - 6特别使这种方法对我来说比方法更有用SubClass.prototype = new SuperClass().其他方法,如dojo的类建模,要复杂得多,我认为是不必要的.
那么,告诉我你的想法.如果其他人之前已经这样做了,请告诉我,我不打算复制任何想法.
您可能想看看 John Resig 对 JavaScript 继承做了什么: http://ejohn.org/blog/simple-javascript-inheritance/
这是我所见过的 Javascript 继承的最佳尝试。