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

前端 未结 3 1027
挽巷
挽巷 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:19

    The two pieces of code are equivalent but the first one is using the ES6 destructuring assignment to be shorter.

    Here is a quick example of how it works:

    const obj = {
      name: "Fred",
      age: 42,
      id: 1
    }
    
    //simple destructuring
    const { name } = obj;
    console.log("name", name);
    
    //assigning multiple variables at one time
    const { age, id } = obj;
    console.log("age", age);
    console.log("id", id);
    
    //using different names for the properties
    const { name: personName } = obj;
    console.log("personName", personName);

提交回复
热议问题