问题描述
我理解行为的区别。 Date()
返回表示当前日期的String, new Date()
返回Date对象的实例,我可以打电话的方法。
I understand the difference in behavior. Date()
returns a String representing the current date, and new Date()
returns an instance of the Date object whose methods I can call.
但我不知道为什么。 JavaScript是原型,因此 Date
是一个函数和一个对象,它具有也是对象的成员函数(方法)。但我没有编写或阅读任何行为方式的JavaScript,我想了解其中的区别。
But I don't know why. JavaScript is prototyped, so Date
is a function and an object which has member functions (methods) which are also objects. But I haven't written or read any JavaScript that behaves this way, and I'd like to understand the difference.
有人可以给我看一些函数的示例代码有一个方法,用new运算符返回一个实例,并在直接调用时输出一个String?即如何发生这样的事情?
Can somebody show me some sample code of a function that has a method, returns an instance with the new operator, and outputs a String when called directly? i.e. how does something like this happen?
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!
非常具体的要求,我知道。我希望这是件好事。 :)
Very specific request, I know. I hope that's a good thing. :)
推荐答案
大部分都可以自己做。根据ECMA规范,在没有 new
的情况下调用裸构造函数并获取字符串对于 Date
是特殊的,但是您可以模拟某些东西类似的。
Most of this is possible to do yourself. Calling the bare constructor without new
and getting a string is special for Date
per the ECMA spec, but you can simulate something similar for that.
这是你如何做到的。首先在构造函数模式中声明一个对象(例如,一个用 new
调用的函数,它返回这个
reference:
Here's how you'd do it. First declare an object in the constructor pattern (e.g. a function that is intended to be called with new
and which returns its this
reference:
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;
};
新事物可以在它们上面调用 instanceMethod()
。现在只需在Thing上添加一个静态函数:
New instances of Thing can have instanceMethod()
called on them. Now just add a "static" function onto Thing itself:
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();
这篇关于为什么我在JavaScript中需要`date`关键字作为'Date`的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!