简体   繁体   中英

Does a Javascript Object Destructure assignment use const, let, or var?

In ES6/ES2015 I can use Object destructuring to pull fields from objects passed as function parameters:

function userId({id}) {
  return id;
}

var user = { 
  id: 42, 
};

console.log("userId: " + userId(user)); // "userId: 42"

In the above example, is the id variable set in the userId function equivalent to setting it via var , const , or let ?

So which of the below is the equivalent function:

Var

function userId(user) {
    var id = user.id
    return id;
}

Let

function userId(user) {
    let id = user.id
    return id;
}

Const

function userId(user) {
    const id = user.id
    return id;
}

(Example function from MDN page linked above, jump to "Pulling fields from objects passed as function parameter)

Declaring variables with destructuring uses the same scope as if you'd declared ordinary variables in the same position. So if you do:

let {id} = {id: 42};

then it's a let binding, if you do:

var {id} = {id: 42};

then it's a var binding.

Function parameters are like var bindings, since they're scoped to the entire function and they're not const . They're also like let bindings because they're scoped to the current block, which is the entire function body.

它将是一个作用于整个函数的局部变量(与所有函数参数一样),如第一个和第二个示例(它们是等效的:在函数顶部时letvar之间没有区别)。

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