Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it guaranteed that `Math.cos(0) === [Math.cos][0](0)`?

In Javascript it's different to use a.b(c) or [a.b][0](c) the reason being the binding of this to the object a or not during the execution of the code of a.b.

Following the same reasoning using

var z = Math.cos;
console.log(z(1));

could in theory be different from console.log(Math.cos(1)) but doesn't seems so in practice.

The question is: is it guaranteed by the standard that for predefined objects like Math, Symbol or Object the this context is irrelevant in a compliant implementation?

With Math the question seems silly, as apparently there's no reason to depend on the context... however for example for Symbol.for it's reasonable to assume that an implementation could store the global symbol table in an object member and in that case using [Symbol.for][0]("x") wouldn't work.

Symbol.for indeed seems to work fine without context in node, chrome and firefox, but I wonder if this is guaranteed or just incidental...

like image 818
6502 Avatar asked Aug 11 '17 22:08

6502


People also ask

What does Math cos do?

cos() The Math. cos() function returns the cosine of a number in radians.

Does Math Cos return radians or degrees?

cos() returns the cosine of a number (radians) that is sent as a parameter.

What is the use of math object in JavaScript?

The JavaScript Math object allows you to perform mathematical tasks on numbers.


1 Answers

Nothing in the specification of the Math object mentions any use of the this value.

Since other parts of the specification are clear when a function depends on this, I believe this indicates that the context is not relevant to these functions, and you can safely call them without any context.

like image 175
Barmar Avatar answered Sep 25 '22 00:09

Barmar