开发者

What is the difference between new Foo and new Foo() in javascript?

I know the diff开发者_如何学Goerence between two in C++, but don't know if it's the same for JS also


From my experience there is no difference other then with new Foo you can't pass any parameters and with new Foo() you can.


From the ECMAScript Language Specification for new:

new NewExpression:

Call the [[Construct]] method on Result(2), providing no arguments

new MemberExpression Arguments

Call the [[Construct]] method on Result(2), providing the list Result(3) as the argument values.

It's simply a matter of whether the constructor receives any arguments or not.


Foo() calls a function, new Foo() instantiates an object of type foo. If you have a prototype defined, all the methods and instance variables defined within it get instantiated as well.

function Foo() {}

Foo.prototype = {
   myVar: 'Some val',
   sayFoo: function () {alert(this.myVar);}
}


var foo = new Foo();
foo.sayFoo();

That will alert 'Some Val'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜