Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite function using prototype in javascript?

In the following example I expect that createProduct function will be overwritten. But the result is the error.

var AbstractFactory = function(){
  this.createProduct = function(){
    throw new Error("The createProduct() method has not been implemented.");
  }
}

AbstractFactory.prototype.createProduct = function(){
  console.log('The method has been overwriten successfully');
};

var factory = new AbstractFactory();
factory.createProduct();
like image 647
Warlock Avatar asked Jun 15 '26 22:06

Warlock


2 Answers

The search for properties starts with the object itself, and only when no property is found is the prototype checked. Thus, the first "createProduct" function found on your "factory" object is the error function. If you initialize the object and the prototype in the other order, then you'll get the results you expect.

Note that the properties on the prototype object do not cause properties to come into existence on instance objects created with the constructor.

like image 136
Pointy Avatar answered Jun 17 '26 13:06

Pointy


The problem is that there is no such thing as Abstraction in JavaScript. One way you can implement what you want is to use a more modular approach. When you create the factory object, you can pass a function into the AbstractFactory function that will override the createProduct function.

var AbstractFactory = function(func){
  this.createProduct = func || function(){
    throw new Error("The createProduct() method has not been implemented.");
  }
}


var factory = new AbstractFactory(function() {
  console.log('The method has been overwriten successfully');
});
factory.createProduct();  // The method has been overwriten successfully

You also might want to check first that func is a function before assigning it to createProduct.

like image 39
Steven Lambert Avatar answered Jun 17 '26 12:06

Steven Lambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!