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();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With