15

我理解行为上的差异。Date()返回一个表示当前日期的字符串,并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!

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

4

2 回答 2

4

大部分都可以自己做。根据 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;
};

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

Thing.staticMethod = function() {
    alert("static method called");
};

现在你可以这样做:

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();
于 2010-08-27T19:57:29.807 回答
-1

new是 Javascript(和其他)中的关键字,用于创建对象的新实例。
可能重复什么是 JavaScript 中的“新”关键字?.
另见这篇文章:http ://trephine.org/t/index.php?title=Understanding_the_JavaScript_new_keyword

于 2010-08-27T19:50:49.037 回答