Home > Web Front-end > JS Tutorial > body text

Prototype vs. Constructor-Defined Methods: Which is Best for JavaScript?

Patricia Arquette
Release: 2024-11-20 13:49:14
Original
150 people have browsed it

Prototype vs. Constructor-Defined Methods: Which is Best for JavaScript?

Advantages of Prototype vs. Constructor-Defined Methods

When defining methods in JavaScript, developers can choose between implementing them as prototype methods or declaring them directly in the constructor. Both approaches have their advantages:

Prototype-Defined Methods

  • Universal Changes: Prototype methods can be updated globally for all instances of a class, while constructor-defined methods require updates for each instance individually.
  • Improved Performance: Prototype methods are created once and shared by all instances, reducing repetitive method creation.

Example:

function Class() {}
Class.prototype.calc = function (a, b) {
  return a + b;
}

// Two instances share the same calc() method
var ins1 = new Class(),
    ins2 = new Class();
console.log(ins1.calc(1,1), ins2.calc(1,1)); // Outputs 2, 2

// Updating the prototype method affects both instances
Class.prototype.calc = function() {
  return Array.prototype.slice.apply(arguments).reduce((a, b) => a + b);
}
console.log(ins1.calc(1,1,1), ins2.calc(1,1,1)); // Outputs 3, 3
Copy after login

However, prototype methods cannot access private variables defined inside the constructor.

Constructor-Defined Methods

  • Access to Private Variables: Public methods defined in the constructor have access to private variables, unlike prototype methods.

Function vs. Variable Declaration for "Class"

Regarding the choice between using function literals (e.g., var Class = function () {}) or function declarations (e.g., function Class () {}), the latter is preferred because it allows "hoisting" of the function name to the top of the scope, avoiding potential errors caused by calling the function before it has been defined.

The above is the detailed content of Prototype vs. Constructor-Defined Methods: Which is Best for 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