从对象(Date对象)解构函数 [英] Destructuring a function from object ( Date Object )

查看:25
本文介绍了从对象(Date对象)解构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If i want to destruct an Object i would do :

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

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

const {
  a,
  fn
} = obj;

console.log( fn() );

这不适用于 Date 对象

未捕获的TypeError:这不是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 可能?如果可能的话,如何实现?

Why is this possible with the first Object and not with the Date ? how would one acheive that if it's possible.

推荐答案

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

Because this it not a Date object. When you call getDate() without its proper context (ie. date.getDate()), then you're calling it in the context of the window (or null in strict mode). Neither window nor null are Date objects, therefore the function fails.

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

这篇关于从对象(Date对象)解构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆