Home >Web Front-end >JS Tutorial >How to Choose Between Prototyping and Closure for Creating Custom Objects in JavaScript?

How to Choose Between Prototyping and Closure for Creating Custom Objects in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 17:33:14985browse

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:

  • Lightweight and native to JavaScript
  • Reuses existing prototype
  • Supports instanceof

Disadvantages:

  • Base constructor must be called in subclass constructor
  • Requires handling constructor when subclassing

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:

  • Prevents instance sharing of methods
  • Automatic binding of methods to instances

Disadvantages:

  • Less efficient due to per-instance method copies
  • Cannot use instanceof without custom logic

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!

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