Replaced
Object(obj)
With
{}.constructor(obj)
Are they exactly equivalent?
Initial testing suggests they are.
Why does the second version pass jslint and not the first?
Replaced
Object(obj)
With
{}.constructor(obj)
Are they exactly equivalent?
Initial testing suggests they are.
Why does the second version pass jslint and not the first?
Here is a summary of the difference (taken from jslinterrors):
// Overwrite the Object function.
window.Object = 10;
// Execution of the following will raise:
// "TypeError: number is not a function" (Chrome)
var x = new Object();
The object literal notion var x = {};
succeeds regardless of the state of window.Object.
Not sure if you were simplifying those, but neither statements look particularly great. Crockford indeed advises against the new Object()
notation and prefers {}
which you'll see a lot of js developers follow.
Using var Something = {}
vs var Something = new Object()
saves you characters in the end, but in the end, it's really a matter of preference. Also some people will tell you it's easier to read when you use an object literal. And as listed here as a 3rd reason, it won't matter if someone overwrites the Object function.
There are some advantages to using each and this question had a bigger discussion about it.
Either way if you're doing new Object()
and have the /*jshint newcap:true*/
option enabled, you should be fine.
Are they exactly equivalent?
No. One could either overwrite the global Object
variable or the Object.prototype.constructor
property to get distinct results.
Why does the second version pass jslint and not the first?
The "error" message should tell you:
Use the object literal notation {} or Object.create(null).
This message actually should [only] show up for usages of new Object
(where it is quite legitimate, since Crockford considers new
harmful and object literal notation is cleaner). For some reason jslint puts up the warning for your code as well, although it does not apply. Never trust JsLint, it doesn't understand your code but only scans it for beginner-mistake-patterns.
Your usage of the Object
function is totally fine, you are not trying to create a new object.
It is not only fine, for most cases it is the ONLY solution! Object.create(undefined) vs. Object(undefined) as suggested, results in a TypeError!
It also results in unnecessary (and even broken) copies of objects: Object.create(new Date()).getDate();