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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.