我已经做了很多的阅读。我写了很多虚拟代码。当我一劳永逸地征服JavaScript继承时,我仍然和我一样困惑。也许更是如此。Javascript原型类继承
我非常钦佩Backbone.js
,我喜欢它的使用集合。所以我阅读了源代码并感受到了启发。但是我继续跳过继承与扩展对象的关系。
这里,作为最好的,我可以推断出一个Javascript类继承,用于该用途的目的,我看不出在使用扩展benfit:
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
)_models
财产直接在Employees
但它的工作原理。这种方法有什么问题吗?任何gottchas或警告?我不想建立一个应用程序,以找出它的一点点... ...。
编辑 它可能是值得注意的一个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();
谢谢。我今天晚上试试看它。学习Javascript“课程”真的让我失望 – JonWells
真的很有帮助,谢谢 – JonWells