Reputation: 10585
The Javascript microlibrary augment.js is sometimes used to include OOP-like features in Javascript code. Despite working with Javascript on a daily basis I am still somewhat naive about the inner workings of the language, so I often rely on or borrow from patterns from other libraries to avoid pitfalls.
One function in the augment.js
library is defclass
, which is quite short:
augment.defclass = function (prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
};
My question is: how is this anything like defining a class? It looks like all it does is 1) set the prototype
of the input's constructor
to be the input itself, and then 2) return the constructor
. What does that have to do with defining a class (or something like a class)?
Upvotes: 1
Views: 92
Reputation: 4971
how is this anything like defining a class?
The question you need to answer first is: What is a class in Javascript?
From: Object vs Class vs Function
As you must already be aware by now there are no classes in JavaScript. Instead functions in JavaScript may be made to behave like constructors by preceding a function call with the new keyword. This is known as the constructor pattern.
From: JavaScript: The Good Parts Douglas Crockford, O'Reilly Media, 8 May 2008, page 29
If a function is invoked with the
new
prefix, then a new object will be created with a hidden link to the value of the function'sprototype
member, andthis
will be bound to that new object.
So again there are no classes - you have functions that can be invoked with new
. If those functions have a prototype
property, then the new objects created are inheriting from that prototype.
Everything you need to do to define a Javascript function to be used as a constructor is setting the properties you want instances to inherit on its prototype property and (as you pointed out in your question) augment.defclass
is doing that.
The reason for having such a function has been already explained by minitech in his answer.
Upvotes: 2
Reputation: 225064
A class defined like this:
var Thing = augment.defclass({
constructor: function () {
this.x = 5;
},
getX: function () {
return this.x;
}
});
A typical JavaScript constructor:
function Thing() {
this.x = 5;
}
Thing.prototype.getX = function () {
return this.x;
};
They both have the same effect, but the defclass
version looks more familiar to users of other languages. One extracts the constructor from the prototype, and the other puts the prototype on the constructor.
Upvotes: 4