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...
cos() The Math. cos() function returns the cosine of a number in radians.
cos() returns the cosine of a number (radians) that is sent as a parameter.
The JavaScript Math object allows you to perform mathematical tasks on numbers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With