如果我想破坏一个对象我会这样做:
const obj = {
a: 'a',
fn: () => 'some function'
}
// const fn = obj.fn;
// OR
const {
a,
fn
} = obj;
console.log( fn() );
这不适用于Date
目的 :
未捕获的类型错误:这不是日期对象。
const date = new Date();
const day = date.getDate();
console.log(day); // works
const {
getDate
} = date;
console.log( getDate() ); // doesn't work
为什么第一个对象可以做到这一点,而第二个对象却不能做到这一点?Date
?如果可能的话,如何实现这一目标。
Because this
它不是日期对象。你打电话时getDate()
没有适当的上下文(即date.getDate()
),然后你在上下文中调用它window
(or null
在严格模式下)。两者都不window
nor null
是 Date 对象,因此函数失败。
Try const getDate = date.getDate.bind(date);
Demo:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)