TypeError:这不是Date对象

TypeError: this is not a Date object

本文关键字:对象 Date 这不是 TypeError      更新时间:2023-09-26

知道为什么这在Chrome中不起作用吗
var foo = (new Date).getDate;
foo();

我得到一个TypeError:这不是Date对象。然而(new Date).getDate()在上工作

在您的示例中,函数没有正确绑定。该foo调用的"this"对象不是原始日期对象。

使逻辑工作的一种方法是绑定函数:

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

在JavaScript中,this上下文是而不是绑定到对象的每个方法。相反,它是在运行时由调用该方法的方式决定的。有关绑定行为的更多信息,请查看此答案。。

在您的代码中,foo接收new DategetDate属性,它通过原型链从Date.prototype接收该属性。因此,您的代码实际上相当于:

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

(自己测试:在控制台中验证(new Date).getDate === Date.prototype.getDate确实是true。)

现在,应该清楚的是,该调用没有实际的this上下文。您可以通过手动将函数bind添加到对象来预先设置它。(注意:较旧的浏览器需要Function.prototype.bind的shiv。)

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

或者,在call/apply函数时设置正确的this上下文。

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

问题是,当您调用函数时,this不是日期,而是全局上下文(window)。

你可以这样做:

foo.call(new Date());

或者,如果你想在任何地方使用该功能,并且仍然使用原始日期,你可以使用

var date = new Date();
var foo = function() { return date.getDate() }; // returns always the same date

var foo = function() { return (new Date()).getDate() }; // returns the current date

如果没有IE8,你也可以使用bind:

var foo = date.bind(date);

您想要做的是

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

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

当您像以前那样调用foo时,它不会引用日期对象,这就是它抛出错误的原因。

因为代码中的foo只是一个不与任何对象绑定的函数。它需要来自Date对象的一些其他信息才能被调用。你可以这样做:
var date = new Date()
var foo = date.getDate
foo.call(date)