Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么它打印窗口对象而不是打印日期对象?_Javascript - Fatal编程技术网

Javascript 为什么它打印窗口对象而不是打印日期对象?

Javascript 为什么它打印窗口对象而不是打印日期对象?,javascript,Javascript,我遇到了这个密码。我希望这个是日期,而不是窗口对象。我正在Firefox scratchpad中运行这个。我错过了什么 Date.prototype.nextDay=function(){ console.log('打印此'+此); var currentdate=this.getDate(); 返回新日期(this.setDate(currentdate+1)); } (功能(){ 变量日期=新日期(); 文件。书写(日期); document.write(date.nextDay());

我遇到了这个密码。我希望
这个
是日期,而不是窗口对象。我正在Firefox scratchpad中运行这个。我错过了什么

Date.prototype.nextDay=function(){
console.log('打印此'+此);
var currentdate=this.getDate();
返回新日期(this.setDate(currentdate+1));
}
(功能(){
变量日期=新日期();
文件。书写(日期);
document.write(date.nextDay());

})();您与JavaScript隐匿的自动分号插入(或者在本例中,缺少分号)发生了冲突

你所想的是两种不同的说法:

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

被解释为一个单独的语句:

Date.prototype.nextDay = function () { ... }(function () { ... })();
第一个匿名函数立即被调用,第二个匿名函数作为其参数

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

在一行的开头有一个圆括号是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())
})()

当我运行你的代码时它会打印一个日期是的。。但它也应该打印第二天的日期。我看到三个日期,其中一个日期定在明天……这也是我看到的。试着放一个
在屏幕截图第5行的
}
之后。问题中有分号,但屏幕截图中没有。这可能就是问题所在。
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())
})()