Difference between Class(), new Class and new Clas

2019-06-27 09:06发布

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.

3条回答
在下西门庆
2楼-- · 2019-06-27 09:22

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-06-27 09:26

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

查看更多
迷人小祖宗
4楼-- · 2019-06-27 09:40

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,

查看更多
登录 后发表回答