Creating Custom Objects
There are two primary ways to create custom objects in JavaScript: the prototyping way and the closure way.
Prototyping Way
With this method, the object's properties and methods are defined on its prototype. The following example creates a Shape object and a Circle object that subclasses the Shape:
function Shape(x, y) { this.x = x; this.y = y; } Shape.prototype.toString = function() { return 'Shape at ' + this.x + ', ' + this.y; }; function Circle(x, y, r) { Shape.call(this, x, y); // Invoke base class constructor this.r = r; } Circle.prototype = new Shape(); // Create prototype inheritance link Circle.prototype.toString = function() { return 'Circular ' + Shape.prototype.toString.call(this) + ' with radius ' + this.r; };
Closure Way
This method does not use inheritance. Instead, each instance has its own copies of properties and methods.
function Shape(x, y) { var that = this; this.x = x; this.y = y; this.toString = function() { return 'Shape at ' + that.x + ', ' + that.y; }; } function Circle(x, y, r) { var that = this; Shape.call(this, x, y); // Invoke base class constructor this.r = r; var _baseToString = this.toString; this.toString = function() { return 'Circular ' + _baseToString.call(that) + ' with radius ' + that.r; }; };
Pros and Cons
Prototyping Way
Closure Way
Choosing the Right Method
The choice depends on the specific requirements of the project. For large object hierarchies with multiple levels of inheritance, prototyping may be preferred. For simple, independent objects, the closure way is often more convenient.
The above is the detailed content of What are the Prototyping and Closure Ways to Create Custom Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!