Javascript TypeError:这不是日期对象
知道为什么这在Chrome中不起作用吗?Javascript TypeError:这不是日期对象,javascript,Javascript,知道为什么这在Chrome中不起作用吗? var foo=(新日期).getDate foo() 我得到一个TypeError:这不是日期对象。但是(新日期).getDate()有效在您的示例中,函数没有正确绑定。该foo调用的“this”对象不是原始日期对象 使逻辑工作的一种方法是绑定函数: var x = new Date(); var foo = x.getDate.bind(x); foo(); 问题是调用函数时,此不是日期,而是全局上下文(窗口) 您可以这样做: foo.call(n
var foo=(新日期).getDate
foo()代码>
我得到一个TypeError:这不是日期对象。但是(新日期).getDate()
有效在您的示例中,函数没有正确绑定。该foo调用的“this”对象不是原始日期对象
使逻辑工作的一种方法是绑定函数:
var x = new Date();
var foo = x.getDate.bind(x);
foo();
问题是调用函数时,此
不是日期,而是全局上下文(窗口
)
您可以这样做:
foo.call(new Date());
或者,如果您希望能够在任何地方使用该函数,并且仍然使用原始日期,则可以使用
var date = new Date();
var foo = function() { return date.getDate() }; // returns always the same date
或
如果没有IE8,您还可以使用:
你想做的是
var date = new Date;
var foo = date.getDate.bind(Date)
foo()
或
当您像这样调用foo
时,它不会引用日期对象,这就是它抛出错误的原因。因为代码中的foo
只是一个不与任何对象绑定的函数。它需要来自Date
对象的一些其他信息才能被调用。您可以这样做:
var date = new Date()
var foo = date.getDate
foo.call(date)
在JavaScript中,此
上下文未绑定到对象的每个方法。相反,它是在运行时通过调用该方法的方式确定的
在代码中,foo
接收new Date
的getDate
属性,该属性通过原型链从Date.prototype
接收。因此,您的代码实际上相当于:
var foo = Date.prototype.getDate;
foo();
(自己测试:在控制台中验证(新日期).getDate==Date.prototype.getDate
确实是true
)
现在,应该很清楚,该调用没有实际的this
上下文。您可以通过手动将函数绑定到对象来预先设置它。(注意:对于函数.prototype.bind
)
或者,在调用函数时设置适当的此上下文
var foo = Date.prototype.getDate;
foo.call(new Date);
如果您无意中发现了这个问题,并且正在使用代理
,请阅读以下内容:
var date = new Date()
var foo = date.getDate
foo.call(date)
var foo = Date.prototype.getDate;
foo();
var foo = Date.prototype.getDate.bind(new Date);
foo();
var foo = Date.prototype.getDate;
foo.call(new Date);