如果我想破坏我会做的对象:
const obj = {
a: 'a',
fn: () => 'some function'
}
// const fn = obj.fn;
// OR
const {
a,
fn
} = obj;
console.log( fn() );
这不适用于 Date
对象:
Uncaught TypeError: this is not a Date object.
const date = new Date();
const day = date.getDate();
console.log(day); // works
const {
getDate
} = date;
console.log( getDate() ); // doesn't work
为什么第一个 Object 可以做到这一点而不是 Date
?如果可能的话,人们将如何实现这一目标。
最佳答案
因为 this
它不是 Date 对象。当您调用 getDate()
时没有其适当的上下文(即 date.getDate()
),那么您是在 window< 的上下文中调用它
(或在严格模式下为 null
)。 window
和 null
都不是 Date 对象,因此函数失败。
试试 const getDate = date.getDate.bind(date);
演示:
const test = { fn : function() { return this.constructor; } };
const normal = test.fn();
console.log(normal); // object
const {fn} = test;
console.log( fn() ); // window
const bound = test.fn.bind(test);
console.log( bound() ); // object
关于javascript - 从对象(日期对象)解构一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447932/