admin管理员组

文章数量:1406740

What are the differences between Class() and new Class, new Class()? I did a test and the later seems to do be quicker.

I read there is no difference, but there appears to be.

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./object-initilzation

I read there is no difference, but there appears to be.

Share Improve this question edited Dec 29, 2012 at 9:47 user1680104 asked Dec 29, 2012 at 9:41 user1680104user1680104 8,9275 gold badges24 silver badges27 bronze badges 8
  • Related question stackoverflow./questions/13376028/… – aug Commented Dec 29, 2012 at 9:49
  • and what about Class()? Also there seems to be a performance difference? – user1680104 Commented Dec 29, 2012 at 9:50
  • Not entirely sure what you mean by that but if I am correct, I believe Javascript just assumes you are trying to call the constructor so it's similar to new Class(). I can't say for sure though so don't take my word for that. – aug Commented Dec 29, 2012 at 9:53
  • The first one Class() has nothing to do here, I think you are confused there – Alexander Commented Dec 29, 2012 at 9:56
  • See the jsperf link. There seems to be a serious difference between Class() and the others. All of them call the constructor. – user1680104 Commented Dec 29, 2012 at 9:57
 |  Show 3 more ments

3 Answers 3

Reset to default 4

Class()

Calls a function. Don't use this on constructor functions.

new Class and new 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.

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

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,

本文标签: javascriptDifference between Class()new Class and new Class()Stack Overflow