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?

asked Jan 7, 2015 at 20:32
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.

answered Jan 7, 2015 at 20:33
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
}
answered Jan 7, 2015 at 20:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.