假设我有以下名为 obj
的 Javascript 对象:
obj = {
val1: {
val2: "Hello World"
}
};
我可以使用如下所示的方法在函数中解构 obj:
function someFunction({ val1: { val2: greeting } }) {
console.log(greeting);
}
为了进行比较,这里有一个更传统的普通函数:
function someFunction(obj) {
console.log(obj.val1.val2); // could have stored this in a "greeting" const for clarity if desired
}
我的问题是,这真的是一种改进吗?当然,利用 greeting
函数体中的内容更加清晰,但是您可以很容易地看到这样的语法如何变得非常密集并且对于更复杂的对象来说难以阅读。从性能的 Angular 来看,解构是否更有效?我很难想象,因为无论如何该对象都应该通过引用传递。也许我在这里遗漏了一些东西。
预先感谢您的想法!
最佳答案
使用对象解构可以在一些小方面简化代码。这些都不是改变生活的重大事情,但我认为一旦人们适应它,他们就会发现它很有用。
它使函数采用的参数更加明确。通常,对于采用
obj
的函数,您被迫读取函数主体以查找哪些键有效,或者检查文档。var foo = function(args) { // hmmm what keys go on args? } var foo = function({ url : url, overwrite : overwrite = false }) { // oh, url and overwrite, and overwrite has a default }
它将一些击键保存在函数体内,以避免必须触及嵌套键。
// forced to continually reach into the args object var foo = function(args) { if (args.nested.something === true) { doFn(args.nested.key); } } // no more reaching, everything is flat var foo = function({ nested : { something : something, key : key } }) { if (something === true) { doFn(key); } }
它允许更好地默认嵌套键。
// old style var foo = function(args) { args = args || {}; args.nested = args.nested || {}; args.nested.foo = args.nested.foo || "fooValue"; args.nested.active = args.nested.active !== undefined ? args.nested.active : true; // can't do || on boolean true or it overwrites passed false } var foo = function({ nested : { foo : foo = "fooValue", active : active = true } = {} } = {}) { console.log(foo, active); } // foo() - "fooValue" true // foo({}) - "fooValue" true // foo({ nested : { foo : "changed" } }) - "changed" true // foo({ nested : { active : false} }) - "fooValue" false
我还用过吗,还没有。但我会的,我需要一点时间来适应它,就像 =>
和模板字符串一样,这两者都是我现在经常使用的。
关于javascript - ES6 论证解构的意义何在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40354095/