Difference between Class(), new Class and new Class()

元气小坏坏 提交于 2019-12-23 12:11:12

问题


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 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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!