"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The reasons and advantages of the prototype method being defined outside the constructor

The reasons and advantages of the prototype method being defined outside the constructor

Posted on 2025-04-19
Browse:268

Why Should Prototype Methods Be Defined Outside the Constructor Function?

Assigning Prototype Methods Within the Constructor Function: Potential Pitfalls

Stylistically, some prefer the following structure for defining prototype methods:

var Filter = function( category, value ){
  this.category = category;
  this.value = value;

  // product is a JSON object
  Filter.prototype.checkProduct = function( product ){
    // run some checks
    return is_match;
  }
};

However, this approach has several drawbacks compared to the alternative structure:

var Filter = function( category, value ){
  this.category = category;
  this.value = value;
};// var Filter = function(){...}

Filter.prototype.checkProduct = function( product ){
  // run some checks
  return is_match;
}

Functional Drawbacks:

  1. Redundant and Inefficient Assignment: The prototype method is assigned multiple times, which is unnecessary and can have performance implications.
  2. Scope Issues: Referencing local variables of the constructor from within the prototype method can lead to unexpected results. For example:
var Counter = function(initialValue){
  var value = initialValue;

  // product is a JSON object
  Counter.prototype.get = function() {
      return value  ;
  }
};

var c1 = new Counter(0);
var c2 = new Counter(10);
console.log(c1.get());    // outputs 10, should output 0

In this scenario, get() returns the value of c2's local variable value instead of c1's because the method closure references the most recently defined value on the prototype.

Other Considerations:

  • Prototyping Outside the Constructor: The first structure prohibits accessing the prototype outside the constructor, potentially limiting flexibility.
  • Method Placement: In the second structure, methods are placed directly on the object rather than the prototype, which may improve performance in some cases.

Conclusion:

While the first structure may be stylistically pleasing, it can introduce functional drawbacks and scope issues. It is generally recommended to assign prototype methods outside the constructor function (as in the second structure) to avoid potential problems.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3