-2
var x = function (){
    this.add = function (a,b){ return a + b;}
}

var x = function (){};
x.add = function (a,b){ return a + b;};

var x = function (){}
x.prototype.add = function (a,b){ return a + b;}

var x = {};
x.add = function (a,b){ return a + b;}

Can someone explain the difference between the various declarations above?

Thanks

Arun
  • 3,036
  • 3
  • 35
  • 57
  • 3
    **1)** one puts a function on `this` inside the function, but we don't know what `this` is. **2)** puts a function on the function. **3)** puts a function on the functions' prototype object. **4)** creates a plain object and puts a function on it. ..... What do you mean by the differences? What don't you understand? What *do* you understand? Do you understand any of those? Your question is vague. –  Jun 29 '13 at 12:27
  • Thanks for your help @CrazyTrain. Got my answer here http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – Arun Jul 01 '13 at 07:16

1 Answers1

2
  1. Declares a 'class' that can be instantiated using new x that will have public method 'add', 'this' here, refers to object itself after it will have been instantiated.

  2. Adds a 'static' method to function x, this is possible because functions are objects.

  3. Adds 'add' function to prototype of x and all instances of x will have it inherited.

  4. Adds a property 'add' to an object x and sets it to function definition. It is like creating an instance without ever have created a class.

Lex Podgorny
  • 2,598
  • 1
  • 23
  • 40
  • Thanks for your answer @Lex. This was a duplicate question of http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript. – Arun Jul 01 '13 at 07:21