I have been using the following template to create objects in javascript.
function FileSpec(directory, filename){
var object = {};
object.full_path = function(){
return directory + '/' + filename;
}
return object;
}
var filespec = FileSpec('tmp', 'index.html');
Are there any particular disadvantages in using the above implementation versus using prototype and new?
function FileSpec(directory, filename){
this.directory = directory;
this.filename = filename;
}
FileSpec.prototype.full_path = function(){
return this.directory + '/' + this.filename
}
var filespec = new FileSpec('tmp', 'index.html');
You can’t use the
instanceofoperator, or theObject.isPrototypeOf()method effectively with 1, but you can with #2.When using
prototypeinheritance, prototype members (methods etc) are defined only once on the prototype. In #1, you’re defining a new group of members on each instance, which is more memory intensive.Compared to: