Home >Web Front-end >JS Tutorial >Prototyping vs. Closure in JavaScript: Which Method Should I Use for Creating Custom Objects?
Understanding Custom Objects in JavaScript
Creating custom objects in JavaScript involves choosing between two main methods: the prototyping way and the closure way.
The Prototyping Way
In the prototyping way, objects are created based on a prototype object. A constructor function is defined, and methods and properties are added to its prototype property. Inheritence is achieved by using the subclassOf() helper function.
The Closure Way
In the closure way, each object is a standalone entity, with its own copies of methods and properties. Instead of inheritance, copies of methods are passed around as closures. By default, this refers to the current object, which helps with event handling.
Which Way to Use
The best approach depends on your specific needs:
Sample Code for Custom Object
Using the prototyping way:
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); this.r = r; } Circle.subclass(Shape); Circle.prototype.toString = function() { return 'Circle at ' + this.x + ', ' + this.y + ', with radius ' + this.r; };
Using the closure way:
function Shape(x, y) { var that = this; that.x = x; that.y = y; that.toString = function() { return 'Shape at ' + that.x + ', ' + that.y; }; } function Circle(x, y, r) { Shape.call(this, x, y); this.r = r; var _baseToString = this.toString; this.toString = function() { return 'Circle at ' + _baseToString.call(that) + ', with radius ' + this.r; }; }
The above is the detailed content of Prototyping vs. Closure in JavaScript: Which Method Should I Use for Creating Custom Objects?. For more information, please follow other related articles on the PHP Chinese website!