我知道很多不同的JavaScript继承方法。我认为最重要的因素之一是代码助手和大纲是否仍然使用继承模型。
例如,在ExtJS中,继承涉及到:
MyApp.SuperWindow = Ext.extend(Ext.Window, {
constructor: function() {
this.doSomething();
MyApp.SuperWindow.superclass.constructor.apply(this, arguments);
},
doSomething: function() {
}
});我们的SuperWindow扩展了Ext的Window组件,增加了执行某些操作的功能。虽然这种继承可以工作,但您会丢失代码助手和我所知道的所有IDE (Eclipse、Netbeans、Aptana、NuSphere等)中的大纲。
但是,您可以执行以下操作:
MyApp.SuperWindow = {
constructor: function() {
this.doSomething();
MyApp.SuperWindow.superclass.constructor.apply(this, arguments);
},
doSomething: function() {
}
});
MyApp.SuperWindow = Ext.extend(Ext.Window, MyApp.SuperWindow);但这看起来太可怕了。您需要输入MyApp.SuperWindow三次(不包括可以用this编写的父构造函数调用)。
在维护代码助手和大纲的同时,如何在JavaScript中进行继承?
我想保留继承模型的父/超级的概念。由于典型的继承只涉及将对象的副本放入一个人的原型中,因此您不会得到supers这样的东西。
发布于 2010-12-25 17:36:34
我非常喜欢John Resig的Simple Javascript Inheritance,它的语法非常简洁,例如:
var Person = Class.extend({
init: function(forename, surname)
{
this.Forename = forename;
this.Surname = surname;
}
});
var Employee = Person.extend({
init: function(forename, surname, role)
{
this._super(forename, surname);
this.Role = role;
}
});
var employee = new Employee("Matthew", "Abbott", "Developer");
console.log(employee.Forename + " " + employee.Surname + " is a " + employee.Role);
console.log(employee instanceof Class);
console.log(employee instanceof Person);
console.log(employee instanceof Employee);https://stackoverflow.com/questions/4529883
复制相似问题