what is the difference between const and const {} in javascript

前端 未结 3 1032
挽巷
挽巷 2020-11-28 20:06

When I study electron, I found 2 ways of getting BrowserWindow object.

const {BrowserWindow} = require(\'electron\')

and

co         


        
3条回答
  •  囚心锁ツ
    2020-11-28 20:29

    This is one of the new features in ES6. The curly braces notation is a part of the so called destructuring assignment. What this means is that, you no longer have to get the object itself and assign variables for each property you want on separate lines. You can do something like:

    const obj = {
      prop1: 1,
      prop2: 2
    }
    
    // previously you would need to do something like this:
    const firstProp = obj.prop1;
    const secondProp = obj.prop2;
    console.log(firstProp, secondProp);
    // etc.
    
    // however now you can do this on the same line:
    const {prop1, prop2} = obj;
    console.log(prop1, prop2);

    As you have seen in the end the functionality is the same - simply getting a property from an object.

    There is also more to destructuring assignment - you can check the entire syntax in MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

提交回复
热议问题