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.
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