Adam Lee
Adam Lee

Reputation: 25778

What the difference between those two?

Is there any difference between these two:

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

and

var test2 = function() {};
test2.method1 = function() {};

Upvotes: 5

Views: 148

Answers (6)

georg
georg

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:

  • 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.

Upvotes: 4

Steve
Steve

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

jfoliveira
jfoliveira

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

Kenan Banks
Kenan Banks

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

AlexMA
AlexMA

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

qwertymk
qwertymk

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

Related Questions