首页 > 解决方案 > 从对象(日期对象)解构函数

问题描述

如果我想破坏一个对象,我会这样做:

const obj = {
  a: 'a',
  fn: () => 'some function'
}

// const fn = obj.fn;
// OR

const {
  a,
  fn
} = obj;

console.log( fn() );

这不适用于DateObject :

未捕获的 TypeError:这不是 Date 对象。

const date = new Date();

const day = date.getDate();
console.log(day); // works

const {
  getDate
} = date;
console.log( getDate() ); // doesn't work

为什么使用第一个 Object 而不是Date? 如果可能的话,人们将如何实现这一目标。

标签: javascriptdatemethodsthisdestructuring

解决方案


因为this它不是 Date 对象。当您在getDate()没有适当上下文(即。date.getDate())的情况下调用时,您是在 the 的上下文中调用它window(或null在严格模式下)。Date 对象也不windownull,因此该函数失败。

尝试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


推荐阅读