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?
-
1possible duplicate of What is the 'new' keyword in JavaScript?Henrik Andersson– Henrik Andersson01/07/2015 20:33:42Commented Jan 7, 2015 at 20:33
2 Answers 2
The MyClass
function makes no use of this
and has an explicit return
value, so the use of new
has no practical effect whatsoever.
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
}