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
3 Answers
Reset to default 4
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.
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
版权声明:本文标题:javascript - Difference between Class(), new Class and new Class() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744852806a2628596.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论