TypeError:这不是Date对象 [英] TypeError: this is not a Date object

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

问题描述

知道为什么这在Chrome中不起作用?

var foo =(新日期).getDate;

foo();


我得到一个TypeError:这不是Date对象。但是(新日期).getDate()工作

Any idea why this does not work in Chrome?
var foo = (new Date).getDate;
foo();

I get a TypeError: this is not a Date object. However (new Date).getDate() works

推荐答案

在JavaScript中,上下文绑定到对象的每个方法。相反,它是在运行时通过调用方式确定的方法检查此答案以获取更多有关绑定行为。

In JavaScript, the this context is not bound to each method of an object. Rather, it is determined at run-time by the way you call that method Check this answer for more about the binding behaviour..

在您的代码中, foo 收到 getDate 属性新日期,它通过原型链从 Date.prototype 收到。因此,您的代码实际上等同于:

In your code, foo receives the getDate property of new Date, which it receives from the Date.prototype through the prototype chain. Thus, your code is really equivalent to:

var foo = Date.prototype.getDate;
foo();

(自行测试:在控制台中验证(新日期)。 getDate === Date.prototype.getDate 确实是 true 。)

(Test this yourself: verify in your console that (new Date).getDate === Date.prototype.getDate is indeed true.)

现在,应该很清楚,该调用没有实际的这个上下文。您可以通过手动 bind 将该函数预先设置为对象。 (注意:旧浏览器需要shiv for Function.prototype.bind 。)

Now, it should be clear that there's no actual this context for that call. You could set it up beforehand by manually binding the function to an object. (Note: older browsers need a shiv for Function.prototype.bind.)

var foo = Date.prototype.getDate.bind(new Date);
foo();

或者,设置正确的上下文当你打电话 / 申请这个功能。

Alternatively, set up the proper this context when you call/apply the function.

var foo = Date.prototype.getDate;
foo.call(new Date);

这篇关于TypeError:这不是Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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