Is there any difference between these two:
var test1 = function () {
this.method1 = function() {}
}
and
var test2 = function() {};
test2.method1 = function() {};
6 Answers 6
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:
- when called as a standalone function --
test1()--thiswill bewindow - when called as a constructor --
new test1()--thisrefers to the object being created - when called via
callorapply--test1.apply(someObject)--thisrefers to the argument
The second snippet takes the object test2 and assigns a function to its slot named method1.
Comments
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();
1 Comment
test1 is not necessarily a constructor. It could be used as one, but it could also be intended to run in the context of an existing object.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).
Comments
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.
Comments
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.
Comments
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
var test2 = function();