我做了很多阅读。我写了很多虚拟代码。当我开始一劳永逸地征服 JavaScript 继承时,我仍然和我一样困惑。也许更是如此。
我非常钦佩Backbone.js
并且喜欢它对收藏的使用。所以我阅读了源代码并受到启发。但是我一直在继承与扩展对象之间绊倒。
这是,尽我所能推断出一个带有继承的Javascript类,出于这个使用目的,我看不到使用扩展的好处:
function Collection(){
this._models = [];
}
Collection.prototype = {
models: function() {
return this._models;
},
fetch: function() {
console.log("TODO Override fetch method");
},
add: function(model){
this._models.push(model);
$(this).triggerHandler("add", model);
},
}
function Employees(){}
Employees.prototype = new Collection();
Employees.prototype.fetch = function(){
this._models = [new Person("Ron", "male"), new Person("Stevie", "female"), new Person("David Blunkett", "female")];
}
Collection
直接在其中访问 super classes( )_models
属性感觉有点奇怪,Employees
但它确实有效。这种方法有什么问题吗?有任何问题或注意事项吗?我不想为此构建一个应用程序来找出它有点...... naff。
编辑
它可能值得注意的Person
是一个Model
太......
function Model(){}
Model.prototype = {
get: function(attr){
return this.attr;
},
set: function(attr, value){
return this[attr] = value;
}
}
function Person(name, gender){
this.name = name;
this.gender = gender;
}
Person.prototype = new Model();