我想知道如何从字符串中解构默认值。例如,采用以下代码:
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
),但是,我得到了一个错误:未捕获的TypeError:String.prototype.valueOf要求“ this”为
串
我当时以为这是因为我无法从对象中分解方法,但是我的测试却告诉我:
const obj = {
id: 1,
foo: function() {
return "bar";
}
}
const {id, foo} = obj;
console.log(id, foo());
因此,我想知道两件事:
在解构参数时如何将原始字符串传递到函数
f
中(甚至可能吗?)为什么我的第一部分代码出错,而另一部分却没有?
最佳答案
这是不可能的。从对象中解构方法后,只剩下对基本函数的引用,而没有原始对象(或者,在这种情况下是原始字符串)的引用-没有this
来提取值from,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" });
关于javascript - 如何从字符串中解构默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56405928/