javascript - 从对象(日期对象)解构函数
问题描述
如果我想破坏一个对象,我会这样做:
const obj = {
a: 'a',
fn: () => 'some function'
}
// const fn = obj.fn;
// OR
const {
a,
fn
} = obj;
console.log( fn() );
这不适用于Date
Object :
未捕获的 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
? 如果可能的话,人们将如何实现这一目标。
解决方案
因为this
它不是 Date 对象。当您在getDate()
没有适当上下文(即。date.getDate()
)的情况下调用时,您是在 the 的上下文中调用它window
(或null
在严格模式下)。Date 对象也不window
是null
,因此该函数失败。
尝试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
推荐阅读
- odoo - 使用 Odoo 开发人员界面使用来自另一个模型的值计算 many2many 字段
- angular - Angular Component Observable 绑定时间
- sql - 需要一些关于如何通知域用户 ASP.NET 或 SQL 的想法
- python - 如何在不生成新随机数的情况下将参数传递给随机数生成器中的函数?
- memory - 具有 1GB 内存的机器可以在没有交换空间的情况下运行 2GB 二进制文件吗?
- r - R - 地图缩放功能,使绘图成为圆形而不是正方形
- python - 在从 instagram 抓取一些图像的 url 后,我想获得全分辨率图像
- python-3.x - 迭代错误期间字典大小更改
- angular - 向 formBuilder 添加不需要的字段
- python - 如何拆分时间数据(格式为 yyyy-mm-dd hh:mm:ss)来测试和训练集?