Skip to content
Advertisement

How to Bring All of an Objects Properties ForeFront?

Begin:

The Math object in JavaScript can prove to be extremely useful. In a page using the Math object repeatedly, I would rather not continuously use. I would prefer to use these functions at top-level. I will provide an example on how this is possible:

The With Keyword (Bad Way):

Let me state the following: This is absolutely terrible, never use it.

with(Math) {
    let q = min(10,211);
    let r = max(2,8);
    let e = random();
    let p = floor(e*r)
    console.log(q*r/e)
}

Bringing an Object to Front By Defining It As Such (Good Way):

I enjoy using this way much more than the way above.

let {min,max,random,floor} = Math;
let q = min(10,211);
let r = max(2,8);
let e = random();
let p = floor(e*r);
console.log(q*r/e);

Continuation:

I am asking if anyone knows of a way to accomplish what the with keyword does without with because I find with terrible. I am curious to know if it is possible to get all of the words of Math and store it into an Object that is defined as Math. I understand that this may be confusing. Thank you for reading.

Advertisement

Answer

For ordinary objects (instances of the Object class) you could use Object.assign to add their properties to the window object. But for Math and the other base objects their properties seem not to be enumerable. Instead, following this answer you can use Object.getOwnPropertyNames to find all the properties of Math and attach them to the window object.

for (let prop of Object.getOwnPropertyNames(Math)) {
    window[prop] = Math[prop];
}

console.log(PI); // 3.14...

I would suggest this is not a great practice as it is not very transparent about what names are being added to the global namespace.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement