Take a look at this klass
implementation (from Javascript Web Applications by Alex MacCaw.) that adds prototype methods for instantiated objects:
var Class = function(){
var klass = function(){
this.init.apply(this, arguments);
};
klass.prototype.init = function(){};
// Shortcut to access prototype
klass.fn = klass.prototype;
// Shortcut to access class
klass.fn.parent = klass;
// Adding class properties
klass.extend = function(obj){
var extended = obj.extended;
for(var i in obj){
klass[i] = obj[i];
}
if (extended) extended(klass)
};
// Adding instance properties
klass.include = function(obj){
var included = obj.included;
for(var i in obj){
klass.fn[i] = obj[i];
}
if (included) included(klass)
};
return klass;
};
The adding instance properties
bit does not work for me.
var Restaurant = new Class;
Restaurant.prototype = {
init: function(name, cuisine, location) {
this.name = name || 'needs a name';
this.cuisine = cuisine || 'needs a cuisine';
this.location = location || 'needs a location';
}
}
Restaurant.include({
save: function(id) {
return 'saved';
},
destroy: function(id) { /* ... */ },
included: function(klass) {
console.log(klass, " was included!");
}
});
var chow = new Restaurant('Chows', 'chinese', 'mumbai');
The problem is the chow
object does not respond to the save method. The included callback however works.
I get the error: Uncaught TypeError: Object #<Object> has no method 'save'
Why is that? How do I fix it?