Home >Web Front-end >JS Tutorial >How to Choose Between Prototyping and Closure for Creating Custom Objects in JavaScript?
How to Create Custom Objects in JavaScript
JavaScript provides various approaches for creating custom objects. Here are two distinct models:
Prototyping Way
The prototyping model is native to JavaScript. It involves using the prototype property of a constructor function to add properties and methods to instances:
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 constructor this.r = r; } Circle.prototype = new Shape(); // Inherit prototype Circle.prototype.toString = function() { return 'Circular ' + Shape.prototype.toString.call(this) + ' with radius ' + this.r; };
Advantages:
Disadvantages:
Closure Way
The closure model avoids inheritance by using closures to enclose instance-specific data 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); this.r = r; var _baseToString = this.toString; this.toString = function() { return 'Circular ' + _baseToString.call(that) + ' with radius ' + that.r; }; }; var mycircle = new Circle();
Advantages:
Disadvantages:
The above is the detailed content of How to Choose Between Prototyping and Closure for Creating Custom Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!