Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between those two?

Tags:

javascript

Is there any difference between these two:

var test1 = function () {
    this.method1 = function() {}
}

and

var test2 = function() {};
test2.method1 = function() {};
like image 326
Adam Lee Avatar asked May 31 '12 17:05

Adam Lee


2 Answers

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() -- this will be window
  • when called as a constructor -- new test1() -- this refers to the object being created
  • when called via call or apply -- test1.apply(someObject) -- this refers to the argument

The second snippet takes the object test2 and assigns a function to its slot named method1.

like image 167
georg Avatar answered Oct 13 '22 08:10

georg


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();
like image 34
qwertymk Avatar answered Oct 13 '22 09:10

qwertymk