1

I have written some code I found in a video, and it looks something like this:

var clientX = clientX || {} ; 
clientX.MyClass = function(initialValue){
  var var1 = initialValue;
  var publicMembers = {
    get_var1 : function(){
      return var1; 
    }
  };
  return publicMembers;
}



var result = new clientX.MyClass("val1");
alert(result.get_var1());

clientX.instance = new  clientX.MyClass("val2");
alert(clientX.instance.get_var1());


clientX.instance2= new clientX.MyClass("val3");
alert(clientX.instance2.get_var1());

The thing is, after deleting the "new" keyword when I use : var result = new clientX.MyClass("val1"); Nothing is changed, so why the author chose to use it? What's the effect?

  • 1
    possible duplicate of [What is the 'new' keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – Henrik Andersson Jan 07 '15 at 20:33

2 Answers2

5

The MyClass function makes no use of this and has an explicit return value, so the use of new has no practical effect whatsoever.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
3

the new keyword is used as a piece of pseudoclassical instantiation, wherein a constructor object has properties attached to the keyword "this" but no return value is ever written.

var Car = function(){

  this.color = 'blue';
  this.make = 'toyota';
  this.model = 'camry';

}

now, writing var x = new Car() will add the following lines to the interpretation:

var Car = function(){
  var this = {}; //added by new
  this.color = 'blue';
  this.make = 'toyota';
  this.model = 'camry';
  return this; //added by new
}
Liam Schauerman
  • 836
  • 5
  • 9