Created .isInteger (x) number cannot work in IE

Number.prototype.isInteger = Number.prototype.isInteger || function(x) { return (x ^ 0) === x; } console.log(Number.isInteger(1)); 

will display an error in IE10 browser

+7
source share
3 answers

It seems that IE considers DOM objects and Javascript objects separately, and you cannot extend DOM objects with Object.prototype.

IE does not allow the use of a prototype that is not native.

You will need to make a separate function (global if you want), as

 function isInteger(num) { return (num ^ 0) === num; } console.log(isInteger(1)); 
+8
source

Despite possible problems with adding your own prototypes to MSIE, your function body is not suitable for the method added to Number.prototype .

Prototype methods are called on type instances, and the instance is passed as this (and will always be an object, not a primitive).

Therefore, a more correct implementation:

 Number.prototype.isInteger = function() { return (this ^ 0) === +this; } 

using:

 (1).isInteger(); 

If you want to use Number.isInteger(n) instead, you would have to add your function directly to the Number object, and not to its prototype. To do this, on the MDN page for this function there is a strict gasket .

+2
source

Create Polyfill Number.isInteger

 Number.isInteger = Number.isInteger || function(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; }; 

This should solve the problem associated with IE.

0
source

Source: https://habr.com/ru/post/1205158/


All Articles