javascript - 从对象(日期对象)解构一个函数

标签 javascript date methods this destructuring

如果我想破坏我会做的对象:

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)。 windownull 都不是 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/

相关文章:

java - 将时间添加到当前时间会产生 1 分钟的误差 (Kotlin/Java)

c++ - 从主类中实例化的另一个类访问主类实例方法

java - 如何使用方法在同一行中打印 "*"x 次?

php - 对于熟悉 PHP/Javascript/Mysql 的人来说,什么是一个好的非 Web 应用程序开发环境?

javascript - 将 html 存储到 JS 变量中

javascript - jQuery 默默无闻

scala - 数组 ("one", "two").mkString (":") 在方法返回 WrappedArray 中定义,而不是字符串

javascript - DOM 属性是否适用于 Phone Gap android?

PostgreSQL - 跨年获得一致的年周对

javascript - 有时我从 javascript 日期函数中得到一个无效日期