类型错误:这不是日期对象

eve*_*Guy 5 javascript

知道为什么这在 Chrome 中不起作用吗? 我收到一个 TypeError:这不是 Date 对象。然而有效
var foo = (new Date).getDate;
foo();

(new Date).getDate()

Mat*_*ens 1

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

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

var foo = Date.prototype.getDate;
foo();
Run Code Online (Sandbox Code Playgroud)

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

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

var foo = Date.prototype.getDate.bind(new Date);
foo();
Run Code Online (Sandbox Code Playgroud)

this或者,在您call/apply该函数时设置适当的上下文。

var foo = Date.prototype.getDate;
foo.call(new Date);
Run Code Online (Sandbox Code Playgroud)