为什么打印window对象而不是date对象?

Why does it print the window object instead of printing the date object?

本文关键字:对象 date 打印 window 为什么      更新时间:2023-09-26

我看到了这段代码。我希望this是日期而不是窗口对象。我在Firefox的记事本上运行这个。我错过了什么?

这个图像描述了结果

Date.prototype.nextDay = function() {
  console.log('Printing this ' + this);
  var currentdate = this.getDate();
  return new Date(this.setDate(currentdate + 1));
}
(function() {
  var date = new Date();
  document.write(date);
  document.write(date.nextDay());
})();

您遇到了JavaScript的自动分号插入(或者在本例中没有分号插入)。

你认为是两个独立的语句:

Date.prototype.nextDay = function () { ... }

(function () { ... })();

被解释为单个语句:

Date.prototype.nextDay = function () { ... }(function () { ... })();

您的第一个匿名函数被立即调用,第二个匿名函数作为其参数。

由于它没有作为任何对象的方法调用,并且由于您没有在严格模式下运行,因此this正在求值为全局对象。这就解释了你所看到的行为。

在一行的开头有一个开括号是JavaScript解析器无法"猜"出你想结束前一个语句的少数几个地方之一。尽量避免使用分号的人通常会在任何语句开头的圆括号前面加一个分号:

Date.prototype.nextDay = function () {
    console.log('Printing this ' + this)
    var currentdate = this.getDate()
    return new Date(this.setDate(currentdate + 1))
}
;(function () {
    var date = new Date()
    console.log(date)
    console.log(date.nextDay())
})()