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
Release: 2024-12-19 17:33:14
Original
959 people have browsed it

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;
};
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template