Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - What does curly brackets in the `var { ... } = ...` statements do?

Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs:

var { Hotkey } = require("sdk/hotkeys");

and in various chrome Javascript (let statement is being used in place of var),

let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu }  = Components;

I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN.

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

What you're looking at is a destructuring assignment. It's a form of pattern matching like in Haskell.

Using destructuring assignment you can extract values from objects and arrays and assign them to newly declared variables using the object and array literal syntax. This makes code much more succinct.

For example:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var {a, b, c} = ascii;

The above code is equivalent to:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var a = ascii.a;
var b = ascii.b;
var c = ascii.c;

Similarly for arrays:

var ascii = [97, 98, 99];

var [a, b, c] = ascii;

This is equivalent to:

var ascii = [97, 98, 99];

var a = ascii[0];
var b = ascii[1];
var c = ascii[2];

You can also extract and rename an object property as follows:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var {a: A, b: B, c: C} = ascii;

This is equivalent to:

var ascii = {
    a: 97,
    b: 98,
    c: 99
};

var A = ascii.a;
var B = ascii.b;
var C = ascii.c;

That's all there is to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...