Reputation: 3999
What is difference between first and second code? Is there any logical difference?
first:
function test(val) {
this.val = val;
this.get = function () {
return "Hello world";
};
}
second:
function test(val) {
this.val = val;
}
test.get = function () {
return "Hello world";
};
When to add method to constructor, and when to set method after, and why ?
Upvotes: 0
Views: 79
Reputation: 707238
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.
Upvotes: 3
Reputation: 35276
In your first example, JavaScript behind the scenes is creating an object for you which will delegate to the Constructors Prototype on failed lookups and it also returns that object for you. For example,
function test(val) {
//var this = Object.create(test.prototype);
this.val = val;
this.get = function () {
return "Hello world";
};
//return this;
}
So you're essentially adding a method onto every instance object that was created for you every time you invoke the test function.
In the second example you're taking advantage of the fact that functions are just objects in JavaScript and adding a property to the function, which is rather rare.
Upvotes: 1
Reputation: 7315
In the first example, the get
method is only available once a new object is created.
test.get(); // This will throw an error
var a = new test();
a.get(); // This will work.
In the second example, the get
method can be called directly on the test function
test.get(); // This will work.
If you were to put the code into English, it would appear like so
First:
get
function on the return object.Second
get
as a property of the test
function.Upvotes: 1