简体   繁体   中英

Is there a JS “scope block” with object?

Suppose I have an object as such:

var Root = {
    A: {
        AA: ...,
        AB: ...,
        AC: function() {}
    }
};

Is there syntax in JS that supports a "scope block" or something similar, like in pseudo-code, such that I could call the function AC() or get the value AB without having to redundantly write Root.A ?

Something like this

(Root.A) {
    AC();
    console.log(AB);
}

to mean something like this

Root.A.AC();
console.log(Root.A.AB);

At the moment, there is no recommended way of achieving this. We have the with statement, which does exactly what you need it to, but it comes with performance costs and it is explicitly prohibited in strict mode (explained here ).

If for some reason you absolutely need this functionality, you would use with like so:

 var Root = { A: { AA: 5, AB: 6, AC: function() {return 4;} } }; with(Root.A) { console.log(AB); console.log(AA); console.log( AC() ); } 

Edit:

Another way of doing this (also unrecommended) would be to add Root.A to the global window scope like so:

 var Root = { A: { AA: 5, AB: 6, AC: function() {return 3;} } }; // Extend window with Root.A's objects window = Object.assign(window, Root.A); console.log(AA); console.log(AB); console.log( AC() ); 

The tradeoff with the solution above is that you are polluting the global scope (a very bad idea).

Lastly, if you know all of the fields of Root.A ahead of time, you can simply assign the fields to variables in the current scope with the same name:

 var Root = { A: { AA: 5, AB: 6, AC: function() {return 3;} } }; (function() { var AA = Root.A.AA; var AB = Root.A.AB; var AC = Root.A.AC; console.log(AA); console.log(AB); console.log( AC() ); })(); 

This last way would be the preferred way of doing it, but it assumes you know all of the field names ahead of time.

From some version on (ES6 I think) you can use a destructuring assignment and write something like this:

const {AA, AB, AC} = Root.A;
AC();
console.log(AB);

If that helps.

this inside the function references the outer object if that is what you are looking for.

 var Root = { A: { AA: 1234, AB: 'AB text', AC: function() { // this ==== Root return this.AB; } } }; console.log(Root.A.AC()) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM