The second adds a method to the function itself. This is NOT the same as an instance method in the first.
These two are similar in function:
function test(val) {
this.get = function () {};
}
and
function test(val) {
}
test.prototype.get = function() {};
Both create instance methods that will work like this:
var x = new test("hello");
x.get();
But, your second option simply creates a property on the constructor which is not a method of a test created object. It is a static method. When you do this:
function test(val) {
this.val = val;
}
test.get = function () {
return "Hello world";
};
And, then execute this:
var x = new test("hello");
x.get();
You will find that the x
object does not have a .get()
method. That method is only on the constructor itself test.get()
. For a method to exist on new instances of an object, it must either be assigned to the prototype object or assigned to the object after the object is created (e.g. in the constructor or in some other method). Methods attached directly to the constructor function itself as in test.get = function () {}
are just properties of the constructor and are not inherited by objects created by the constructor. They are somewhat analogous to class static methods in other languages. They are not instance methods.