开发者

What's the difference when new operator is applied?

For example, if I would like to display the current date on the p element:

$("p").html('Now is '+Date()); // good
$("p").html('Now is '+new Date()); // good
$("p").html(Dat开发者_开发百科e()); // good
$("p").html(new Date()); // bad

Why the last statement does not display the current date, but the second statement works?


In the first and third lines Date() returns a string of the current date.

In the second one, when you add a Date object to a string it must be converting the date object to a string, so you see what you expect.

In the last line, it returns a date object, which is why it looks wrong.

To read more about Date you may find this useful:

https://developer.mozilla.org/en/JavaScript/Reference/global_objects/date


I am only going to take a stab at this:

// Javascript parser detects string concatenation. Date() is converted to string (default).

("p").html('Now is '+Date());

// Javascript parser detects string concatenation. Date() is converted to string (default).

$("p").html('Now is '+new Date());

// Instance of date via Date() constructor is converted to string by default.

$("p").html(Date());

// new Date() produces an object. Inserting a non-dom recognized object into dom tree throws error.

$("p").html(new Date());


The answers seem to suggest that you're more interested in string concatenation and the Date object. However, the question title suggests you're more concerned with the general behavior of the new operator and objects in JavaScript in general. So maybe this answer is completely irrelevant.

But, for what it's worth, the new operator is what tells the constructor to return an object. It's a shortcut for constructor constructors. Take the following code:

function SomeConstructor(val1, val2) {
    this.val1 = val1;
    this.val2 = val2;
}

var constructed_obj = SomeConstructor('something', 'else');

The above code will (if not executed in strict mode) append values to the global object. Uh oh.

Also not good:

SomeConstructor.prototype = {
    method1: function () { ... },
    method2: function () { ... }
};

var constructed_obj = SomeConstructor();

The above constructed_obj will not have access to method1 or method2. This might not seem like such a big deal, but imagine creating a new Date object without having any way of accessing its methods!

tl;dr:
Sans new, le déluge.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜