Home >Web Front-end >JS Tutorial >Prototype vs. Closure: Which JavaScript Object Creation Method is Right for You?

Prototype vs. Closure: Which JavaScript Object Creation Method is Right for You?

DDD
DDDOriginal
2024-12-11 04:37:09706browse

Prototype vs. Closure: Which JavaScript Object Creation Method is Right for You?

Proper Implementation of Custom JavaScript Objects

JavaScript offers two distinct approaches to creating custom objects with properties and methods: the prototype way and the closure way.

Prototype 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;
};

Closure Way

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

Choice and Considerations

Both methods have advantages and drawbacks.

Prototype Way

  • More efficient for heavy object inheritance
  • Native to JavaScript, facilitating use of instanceof
  • Requires proper constructor invocation in subclasses

Closure Way

  • Every instance has its own copy of methods (less efficient)
  • Simplifies binding of methods to instances
  • No instanceof support, requiring custom checks

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!

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