Reputation: 25778
Is there any difference between these two:
var test1 = function () {
this.method1 = function() {}
}
and
var test2 = function() {};
test2.method1 = function() {};
Upvotes: 5
Views: 148
Reputation: 215059
The first snippet takes this
object, whatever it is, and assigns a function to its slot (field) named method1
. this
can represent different objects, depending upon how test1
is called:
test1()
-- this
will be window
new test1()
-- this
refers to the object being createdcall
or apply
-- test1.apply(someObject)
-- this
refers to the argumentThe second snippet takes the object test2
and assigns a function to its slot named method1
.
Upvotes: 4
Reputation: 2343
The first one sets the method1 property on whatever invokes test1().
The second one defines an empty function and sets the method1 property on test2
Upvotes: 0
Reputation: 2168
The first one:
var test1 = function () {
this.method1 = function() {}
}
Defines the function "test1". Once (and only when) "test1" is called, "this.method1" will be defined as a function, that does nothing.
The second:
var test2 = function() {};
test2.method1 = function() {};
Create the function "test2" and at the same time defines the function "test2.method1", without the need to invoke the first function.
Upvotes: 0
Reputation: 212208
The first version actually creates a method available to all objects instantiated like so:
var o = new test1();
o.test1();
The second simply attached a function as an attribute on the test2 function. If you're familiar with other class-based OO languages, this works kinda like a static method. You will not have access to the this
pointer in the second example.
Upvotes: 0
Reputation: 10214
Assuming syntax was correct, the first is a constructor that gives all test1 objects created via new test1()
a method called method1. The second just adds a function to the constructor object. In javascript, functions are objects which can have properties (including methods).
Upvotes: 0
Reputation: 35354
The first way is a constructor that creates more objects and needs to have the new
keyword:
var mytest1 = new test1();
mytest1.method1();
The second way is ready to use right away:
test2.method1();
Upvotes: 1