Home >Web Front-end >JS Tutorial >Prototype vs. Closure: Which JavaScript Object Creation Method is Right for You?
JavaScript offers two distinct approaches to creating custom objects with properties and methods: the prototype way and the closure way.
This method is more native to JavaScript and leverages the prototype lookup property of constructor functions.
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(); // Set subclass prototype Circle.prototype.toString = function() { return 'Circular ' + Shape.prototype.toString.call(this) + ' with radius ' + this.r; };
This method avoids prototypical inheritance altogether, creating a new closure for each instance.
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 constructor this.r = r; var _baseToString = this.toString; this.toString = function() { return 'Circular ' + _baseToString.call(that) + ' with radius ' + this.r; }; } var myCircle = Circle(); // Using `new` is optional here
Both methods have advantages and drawbacks.
Prototype Way
Closure Way
Ultimately, the best choice depends on the specific project requirements and preferences.
The above is the detailed content of Prototype vs. Closure: Which JavaScript Object Creation Method is Right for You?. For more information, please follow other related articles on the PHP Chinese website!