This message is displayed when JSLint encounters an object that has been constructed using new Object() instead of simply = {}.
In JavaScript, we can declare a new empty object in two ways:
var obj1 = new Object();
var obj2 = {};
I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.
- It is shorter (10 characters to be precise)
- It is easier, and more structured to create objects on the fly
- It doesn’t matter if some buffoon has inadvertently overridden Object
Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:
var obj1 = new Object(); obj1.Name = "A Person"; obj1.TelNo = "12345";
The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?
This is where the object literal notation can help:
var obj1 = {Name:"A Person",TelNo="12345"};
Here we have achieved the same effect in one line of code and significantly fewer characters.
A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).
And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.
A Guide To JSLint Messages
This article is one of a series on the error and warning messages produced by JSLint.
[...] compare with '{b}'. Use the array literal notation []. Use the isNaN function to compare with NaN. Use the object literal notation {}. Variable {a} was used before it was [...]
[...] are reported. In particular, the object literal notation is tolerated. JSLint requires that you use the object literal notation to declare empty objects (instead of new [...]
Doug Crockford discourages the use of new operator. I think this is in his talk “JavaScript: The Good Parts” and his book.
Watch his Google tech talk @ youtube:
http://www.youtube.com/watch?v=hQVTIJBZook
Sorry. A mistake in the above comment:
Doug Crockford “discourage” the user of the new operator.