What is the difference between the two?

Is there a difference between the two:

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

and

var test2 = function() {};
test2.method1 = function() {};
+5
source share
6 answers

The first fragment takes an object this, regardless of what it is, and assigns a function to its slot (field) with a name method1. thiscan represent different objects, depending on how it is called test1:

  • when called as an autonomous function - test1()- thiswillwindow
  • when called as a constructor - new test1()- thisrefers to the object being created
  • when called through callor apply- test1.apply(someObject)- thisrefers to the argument

The second fragment takes an object test2and assigns a function to a slot with a name method1.

+4

- , new:

var mytest1 = new test1();
mytest1.method1();

:

test2.method1();
+1

, , , test1, new test1() , method1. -. javascript - , ( ).

0

, , :

var o = new test1();
o.test1();

test2. OO , . this .

0

:

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 define the function "test2.method1" without requiring a call to the first function.

0
source

The first sets the method1 property on any call to test1 ().

The second defines an empty function and sets the method1 property to test2

0
source

All Articles