问题
What are the differences between Class()
and new Class
, new Class()
? I did a test and the later seems to do be quicker.
http://jsperf.com/object-initilzation
I read there is no difference, but there appears to be.
回答1:
Class()
Calls a function. Don't use this on constructor functions.
new Class
andnew Class()
There is no difference between these, both instantiate a new instance of a class. The parens are optional if there are no arguments being passed and the new
keyword is used.
回答2:
Class()
is a misuse of constructor function. When you call it like this, it has a global scope as the context object and it does not create the new instance of Class. I guess, that the main difference between new Class
and new Class()
is in some arguments optimization, used by certain javascript engined
回答3:
If you have a class like this:
function Test(propVal){
this.prop = propVal;
}
You will get the next results:
Calling Test() This will return "undefined" since Test is working as a constructor
Calling new Test(5) You will get a new instance of Test and that instance will have its "prop" set to 5
Calling new Test You will get a new instance of Test and that instance will have its "prop" set to undefined
I hope this helped.
Thanks,
来源:https://stackoverflow.com/questions/14080448/difference-between-class-new-class-and-new-class