Reputation: 21025
I was writing javascript code for performing mathematical calculations.
For many functions, I need to type something like Math.log()
or Math.PI
or Math.sqrt()
Is there a way to define the "namespace" or something so I can directly access all the functions defined in Math by just saying log()
, PI
or sqrt()
?
Upvotes: 2
Views: 52
Reputation: 2084
Simply remove the (), and you can assign the function to a variable, then call the variable later.
var log = Math.log;
// ...
console.log("log of 5 = " + log(5));
Upvotes: 5
Reputation: 2896
The way to do this is with
with (Math){
console.log(sin(4));
}
inside of the with(Math)
block, you can use the functions defined on Math such as Math.log
Math.sin
etc.
You can find out more about it on MDN
As the comments point out, this is not always considered safe because of the likelihood of name clashes. These potential pitfalls are the same as statements such as using namespace
in another language, except that not all objects were designed to be namespaces. So, use at your own risk, or assign the particular function to a variable as another answer suggests.
Upvotes: 2