Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...