The Difference Between new Object() and Object Literal Notation
Creating objects in JavaScript can be done in two ways: using the constructor-based new Object() syntax or the object literal notation. While both methods appear to achieve the same result, there is a significant difference when adding methods to objects.
Object Literal Notation
When using object literal notation, methods are defined within each individual object, leading to a potential waste of memory if numerous objects or methods are involved.
function Obj(prop) { return { p: prop, sayHello: function() { alert(this.p); }, }; } const foo = new Obj("hello");
Constructor-Based Syntax
In contrast, using the new Object() syntax, methods are defined in the object prototype and shared among all object instances, optimizing memory usage.
function Obj(prop) { this.p = prop; } Obj.prototype.sayHello = function() { alert(this.p); }; const foo = new Obj("hello");
Advantages of Using Object Prototype
By utilizing the constructor-based syntax and object prototype, you gain the following advantages:
The above is the detailed content of Why Choose Object Prototype Over Object Literal Notation for Method Definition in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!