如何从字符串中解构默认值

How to destructure defaults from a string

我想知道如何从字符串中解构默认值。例如,采用以下代码:

function f({length, valueOf}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf()); // Expected: "The string is: foo"
}

f("foo");

上面,我试图获取传入字符串的 length 以及字符串本身(即:通过调用 valueOf),但是,我收到错误消息:

Uncaught TypeError: String.prototype.valueOf requires that 'this' be a String

我以为这是因为我无法从对象中解构方法,但我的测试告诉我并非如此:

const obj = {
  id: 1,
  foo: function() {
    return "bar";
  }
}

const {id, foo} = obj;
console.log(id, foo());

所以,我想知道两件事:

这不可能。一旦你从一个对象中解构了一个方法,你只剩下对基本函数的引用,而不是原始对象(或者,在这种情况下,原始字符串) - 没有 this 来提取来自的值,valueOf 方法将不可调用。

出于类似的原因,如果您的 foo 试图从 obj 中提取值,它不会起作用:

const obj = {
  id: 1,
  foo: function() {
    return this.id;
  }
}

const { foo } = obj;
// at this point, without referencing `foo` again, it's impossible to get the `id` of 1
console.log(foo());

您原来的 foo 之所以有效,是因为它不依赖于任何调用上下文 - 它也可能只是一个独立的函数。

请注意,如果您将 对象 与字符串作为 属性 传递,这是可能的,尽管您必须将字符串放入独立的变量,所以你可能认为它是作弊:

function f({str: { length, valueOf}, str}) {
  console.log("The length is:", length);
  console.log("The string is:", valueOf.call(str)); // Expected: "The string is: foo"
}

f({ str: "foo" });

这与解构无关,解构只是变量赋值的糖分:

  const valueOf = "foo".valueOf;
  valueOf(); // same error

  valueOf.call("other"); // works