开发者

What's the difference between Number.somepropertyormethod and Number().somepropertyormethod?

So the following works:

alert(Number().toString.call(1));

But this does not work:

alert(Number.toString.call(1));

Furthermore, the following works:

alert(Number.prototype.co开发者_JS百科nstructor(1));

But this does not work:

alert(Number().prototype.constructor(1));

Why do we need the parentheses following Number in the first example, and why must we omit the parentheses in the second example?


Number is a constructor object. Called as a function, it allows you to create new number instances. Number() returns the number 0. Number instances have various properties and methods, including toString() and toExponential() (for example). The following two bits of syntax have identical meanings:

Number().toString.call(1);
(0).toString.call(1);

The Number object also has properties of its own. One special property is the prototype property. This is basically a template for new number instances. All properties that exist on Number.prototype exist on number instances as well. So we can add a third bit of identical code to the above two:

Number.prototype.toString.call(1);

Number instances, however, do not have the prototype property, so you can't access Number().prototype. On the other hand, they do have a constructor property, which returns the object that created them, i.e. the Number object. You can then access prototype on this. So our fourth identical bit of code:

Number().constructor.prototype.toString.call(1);

Hopefully this has clarified the relationship between the Number object and number instances. As a last note, all the above bits of code are identical to this, the obviously correct way to do this:

(1).toString();


you can try to check the following :

alert(typeof Number());//number
alert(typeof Number);//function

it is normal that they have different behaviors, they mean different things


I believe in your example Number is a class and Number() is a constructor call which returns an instance of the Number class.


Here are some tips, you seem very confused

  • The constructor function (Number) doesn't have a property called toString. It does have a property called prototype which allows instances to look at that object if a property isn't defined in the object itself.
  • Number() returns an instance, that does have a property called toString through the prototype chain (from Number.prototype.toString). Those instances do not have a prototype property

// So the following works, you're calling the toString Method of Number.prototype 
// and passing 1 as its context
alert(Number().toString.call(1));


// But this does not work:
// Number (the constructor) does not have property called toString, FAIL
alert(Number.toString.call(1));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜