我意识到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;}此设置需要两个约定:
建模类的properties
下面是一个结果示例(粘贴到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我知道以下的缺点:
修改超类原型的inheritance
。
和优点:
implement)
的现有属性即可。
专家3-6特别使这个方法比SubClass.prototype = new SuperClass()方法更有用。其他方法,比如dojo的类建模,要复杂得多,我认为这是不必要的。
告诉我你是怎么想的。如果以前有人这样做过,请告诉我,我不打算重复任何想法。
发布于 2011-11-29 07:13:38
来这里查看使用javascript进行继承的简单且可能最好的方法的人请阅读以下内容,它比我扫描过的所有内容都简单得多:
http://javascript.crockford.com/prototypal.html
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}注: Object.create现在是新浏览器中javascript的一部分,但是通过添加上面的内容,下面的内容也适用于旧的浏览器。
newObject = Object.create(oldObject);发布于 2010-11-05 01:58:15
您可能想看看John对JavaScript继承做了什么:http://ejohn.org/blog/simple-javascript-inheritance/
这是我所见过的最好的Javascript继承尝试。
发布于 2010-11-10 18:51:55
你知道你贴的东西的坏处..。因此,在描述其他模式的缺陷时,请看我的博客,了解我认为最好的方法是什么。
http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
示例:
//Abstraxct base class
function Animal(name) {
this.name = name;
}
Animal.prototype.sayMyName = function () {
console.log(this.getWordsToSay() + " " + this.name);
}
Animal.prototype.getWordsToSay = function () {} // abstract
// --------------------------------
function Dog(name) {
// Call the parent's constructor
Animal.call(this, name);
}
extend(Dog, Animal, {
getWordsToSay: function(){
return "Ruff Ruff";
}
});我发布的代码是一个示例语法。博客文章详细介绍了如何添加语法糖。
重要的是:
动物//真inheritance
https://stackoverflow.com/questions/4088405
复制相似问题