为什么我在JavaScript中需要`date`关键字作为'Date`的实例?

Jus*_*rce 13 javascript syntax new-operator operator-keyword

我理解行为上的差异.Date()返回表示当前日期的String,并new Date()返回我可以调用其方法的Date对象的实例.

但我不知道为什么.JavaScript是原型,因此Date是一个函数一个具有成员函数(方法)的对象,它们也是对象.但我没有编写或阅读任何行为方式的JavaScript,我想了解其中的区别.

有人可以向我展示一个具有方法的函数的示例代码,使用new运算符返回一个实例,并在直接调用时输出一个String吗?即这样的事情是怎么发生的?

Date();                   // returns "Fri Aug 27 2010 12:45:39 GMT-0700 (PDT)"
new Date();               // returns Object
new Date().getFullYear(); // returns 2010
Date().getFullYear();     // throws exception!
Run Code Online (Sandbox Code Playgroud)

非常具体的要求,我知道.我希望这是件好事.:)

Ben*_*tto 5

其中大部分可以自己完成。根据 ECMA 规范,调用裸构造函数而不new获取字符串是特殊的Date,但您可以为此模拟类似的东西。

这就是你应该如何做的。首先在构造函数模式中声明一个对象(例如,一个旨在调用new并返回其this引用的函数:

var Thing = function() {
    // Check whether the scope is global (browser). If not, we're probably (?) being
    // called with "new". This is fragile, as we could be forcibly invoked with a 
    // scope that's neither via call/apply. "Date" object is special per ECMA script,
    // and this "dual" behavior is nonstandard now in JS. 
    if (this === window) { 
        return "Thing string";
    }

    // Add an instance method.
    this.instanceMethod = function() {
        alert("instance method called");
    }

    return this;
};
Run Code Online (Sandbox Code Playgroud)

新的事物实例可能会instanceMethod()调用它们。现在只需在 Thing 本身上添加一个“静态”函数:

Thing.staticMethod = function() {
    alert("static method called");
};
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

var t = new Thing(); 
t.instanceMethod();
// or...
new Thing().instanceMethod();
// and also this other one..
Thing.staticMethod();
// or just call it plain for the string:   
Thing();
Run Code Online (Sandbox Code Playgroud)