Home >Web Front-end >JS Tutorial >Prototyping vs. Closure in JavaScript: Which Method Should I Use for Creating Custom Objects?

Prototyping vs. Closure in JavaScript: Which Method Should I Use for Creating Custom Objects?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 15:07:13542browse

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:

  • Prototyping is better for creating hierarchies of objects with efficient memory usage. It supports the use of instanceof.
  • Closure is preferred when you need to bind methods to specific instances, avoiding the issues of JavaScript's this binding. It can also be more efficient for small and transient objects.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn