Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(Date()); // good
$("p").html(new Date()); // bad

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

like image 554
realguess Avatar asked Jan 29 '11 04:01

realguess


3 Answers

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

like image 111
James Black Avatar answered Nov 14 '22 06:11

James Black


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());
like image 43
bleepzter Avatar answered Nov 14 '22 06:11

bleepzter


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.

like image 1
sdleihssirhc Avatar answered Nov 14 '22 05:11

sdleihssirhc