Home > Article > Web Front-end > 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:
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:
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.
The above is the detailed content of Why Should Prototype Methods Be Defined Outside the Constructor Function?. For more information, please follow other related articles on the PHP Chinese website!