Is there any practical use for overriding Math.constructor in JavaScript / ActionScript?

A Math object does not have a prototype property, but it has a constructor property. Is there a case where it would be useful to override the constructor?

+3
javascript constructor actionscript ecmascript-5 jscript
source share
8 answers

MDN says:

Unlike other global objects, Math is not a constructor. All properties and methods of mathematics are static .

In other languages, when a class is static, you can directly use its properties and methods without creating an instance of this class (object). If the Math constructor is used, there is no built-in type to support the object, unlike the primitive types: Number, String, Boolean. They can be converted to objects with their wrappers.

In addition, it is bad practice to expand the root object. If in the future new features are implemented in the environment, and there is no security check for this code, it will override its own.

My personal opinion is that you are not a constructor or prototype - you can define your own mathematical functions. The Math object is here only to introduce standard functions and to give programmers the opportunity not to define Pi or E , for example. And, probably, the user-defined math function will be several times slower than the built-in one.

+2
source share

The Math object (namely: the object referenced by the initial value of the Math property of the global ECMAScript object) does not have the constructor property, see ECMAScript Language Specification, Version 5.1 , Section 15.8 “Mathematical Object”. Consequently,

 Math.hasOwnProperty("constructor") 

returns false (in accordance with implementations of ECMAScript Ed 3 and higher).

The Math object inherits the constructor property through the prototype chain from its prototype, which is the "standard built-in object prototype of the object (15.2.4)" (ibid.), Which is the same as that originally mentioned by the Object.prototype property. The latter object provides several useful properties, such as Object.prototype.hasOwnProperty (see above). The prototype chain of the Math object is not empty.

The fact that the Math object also inherits Object.prototype.constructor is simply a side effect of this unconditional inheritance in ECMAScript implementations, since (with the exception of implementations of sentences 4 and, possibly, future editions) a suitable visibility modifier to prevent this (e.g. private on multiple class-based languages). And, of course, the Object instance constructor, which inherits from the same prototype, is the object referenced by the initial value of the Object property of the Global object. Therefore, Object.prototype.constructor should reflect this. Therefore, the result of the assessment

 Math.constructor === Object 

is true .

+6
source share

All objects have a constructor property, which indicates the constructor that created the object.

Even ({}).constructor returns Object() .

+5
source share

Actually, Math does not have its own constructor property. It inherits the "constructor" from Object.prototype, just as it inherits "toString", "hasOwnProperty" and all other properties of Object.prototype.

For Math, the "construct" probably has very little utility. This is just a consequence of how JavaScript inheritance works.

+3
source share

Math object "inherits" from Object (which means Math.__proto__ === Object.prototype )

A Math object is nothing more than for any JavaScript programmer than a “special”, but simple Object with applied methods, the implementation and construction of which are automatic and hidden.

Object.prototype defines a .constructor field (virtually any function assigns its own prototype constructor, see ex1)

ex1 (a bit of a workaround):

 function xxx() { } // then: xxx.prototype.constructor === xxx; // true // since xxx is a function: xxx.constructor === Function.prototype.constructor; // true // and as such: xxx.constructor === Function; // true 

As such, when you use the Math.constructor , it just looks for a prototype chain of Math objects like this (... nice view):

  • MathMath.hasOwnProperty('constructor') === false

  • DO NOT FIND NEXT

  • Math.__proto__Math.__proto__.hasOwnProperty('constructor') === true

  • FOUND RETURN: Math.__proto__.constructor

so basically:

 Math.constructor === Object.prototype.constructor; // true // and as such: Math.constructor === Object; // true // and as stated at the top: Math.__proto__ === Object.prototype; // true 

hope this helps -ck

+2
source share

In my opinion, a Math object in JavaScript is trying to mimic the static behavior of Math in other popular programming languages ​​(like Java). Since this can only be modeled in JavaScript, and by default all objects have prototype and constructor properties, I assume that the developers have just forgot to set the constructor undefined property by explicitly doing something like Math.constructor = undefined;

0
source share

In a situation where you need to create a conversion table without polluting the global area, this would be useful. For example:

 Math.constructor = function() { var i = 0, unicode = {}, zero_padding = "0000", max = 9999; //Loop through code points while (i < max) { //Convert decimal to hex value, find the character, then pad zeroes to the codepoint Math.constructor[String.fromCharCode(parseInt(i, 16))] = ("u" + zero_padding + i).substr(-4); i = i + 1; } } 

Run the constructor to populate it as such:

 Math.constructor(); Math.constructor["a"] 

Another option would be to extend the properties and methods for defining primitives for a graph library:

 root (arg, index) "index-th" root of argument.  Example: root (x, 6) sixth root of x, root [tan (x), 4] fourth root of the tangent of x.
 sqrt () Square root of argument (number or expression inside the parentheses).  Equivalent to root (argument, 2)
 cbrt () Cube root of argument.  Equivalent to root (argument, 3)
 logn (arg, base) Logarithm base-base of arg.
 ln () Natural logarithm of argument (base-E logarithm of argument where E is Euler constant)
 lg () Logarithm base-10 of argument, equivalent to logn (argument, 10).
 lb () Logarithm base-2 of argument.
 exp () Exponential Function E to the power of argument, equivalent to E ^ argument
 sin () sine of argument
 cos () Cosine
 tan () Tangent
 cot () Cotangent
 sec () Secant of argument, equiv.  to 1 / cos (arg).
 csc () Cosecant, equiv.  to 1 / sin (arg).
 asin () Arc sine
 acos () Arc cosine
 atan () Arc tangent
 acot () Arc cotangent
 asec () Arc secant, inverse secant.
 acsc () Arc cosecant, inverse cosecant.
 sinh () Hyperbolic sine, Sinus hyperbolicus
 cosh () Hyperbolic cosine, Cosinus hyperbolicus
 tanh () Hyperbolic tangent, Tangens hyperbolicus
 coth () Hyperbolic cotangent, Cotangens hyperbolicus
 sech () Hyperbolic secant, Secans hyperbolicus.
 csch () Hyperbolic cosecant, Cosecans hyperbolicus.
 asinh () Area sine, Area sinus hyperbolicus, inverse sinh ().
 acosh () Area cosine, Area cosinus hyperbolicus, inverse cosh ().
 atanh () Area tangent, Area tangens hyperbolicus, inverse tanh ().
 acoth () Area cotangent, Area cotangens hyperbolicus, inverse cotanh ().
 asech () Area-secant, Area secans hyperbolicus, inverse sech ().
 acsch () Area-cosecant, Area cosecans hyperbolicus, inverse csch ().
 gaussd (x, mean, sigma) Gaussian distribution ("Bell Curve").  gaussd (x, 0,1), by the way, is the special case "Normal distribution density with mean-value = 0, standard-deviation = 1".
 min (arg1, arg2) Returns the lesser of the two arguments
 max (arg1, arg2) Returns the greater of the two arguments
 round () Rounds argument up or down to the closest integer
 floor () Rounds arg down.
 ceil () Rounds arg up.
 abs () or |  |  Absolute value of argument.  Example: 2abs (sin [x]) or alternatively 2 | sin (x) |  .
 sgn () Sign Function. 
 rand Random number between 0 und 1. Example:
 pi * rand * sin (x) or even Pirandsin (x).
 E Euler constant 2.718281828459045 ...
 LN2 Natural logarithm of 2, is 0.6931471805599453 ...
 LN10 Natural logarithm of 10, is 2.302585092994046 ...
 LOG2E Base-2 logarithm of E (E: see above), is 1.4426950408889633 ...
 LOG10E Base-10 logarithmus of E, is 0.4342944819032518 ...
 PHI Golden Ratio 1.61803398874989 ...
 PI 3.141592653589793 ...
 SQRT1_2 Square root of 1/2, is 0.7071067811865476 ...
 SQRT2 Square root of 2, is 1.4142135623730951 ... 

References

0
source share
  <script type="text/javascript"> Math.prototype=Math; Math.prototype.rand=function(min,max){ return Math.floor((Math.random() * (max-min+1))+min) } var o=[]; for(var i=0;i<100;i++)o.push(Math.rand(-1,1)); alert(o.join(", ")) </script> 

Rough you can also just do:

 Math.rand=function(min,max){ return Math.floor((Math.random() * (max-min+1))+min) } 

The reason Math does not have its own prototype, such as Array and String, is because it is not a function, but an object. Since you can use the new String() and the new Array() , you can also use String.prototype and Array.prototype .

The same goes for Object, Function, Number, Date, RegExp and even Boolean . However, a prototype property will be assigned to any specific function and inherited from the function and everything else in the chain from which it should be inherited.

If you want to consider Math as a function, all you have to do is redefine the variable with the function. This way the Math.constructor will not return an Object when called, as it will actually be associated with your custom function that created it.

First, you can make a copy of your own object, and then transfer it to one of the prototype properties of your overriding function or use encapsulation so that only your new Math function can access its own methods. Not sure what else can be said on this issue.

The question of discovery is pointless. Math.constructor will return an object and will be the same as calling the object directly. The only difference is that you changed the constructor.

Why do you want to change the constructor anyway?

The Math object looks great as it is. If we expected him to inherit something, what would we expect " this " to point to anyways? If you can come up with an answer to this question, you will have something with a purpose that you can encode.

-one
source share

All Articles