3

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();
1
  • The factory object has the createProduct method itself, which you haven't overwritten. Commented Aug 7, 2013 at 17:16

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Another example to help a little:

Override using a config to implement the object.

var AbstractFactory = function(config){
  this.init(config)
}

AbstractFactory.prototype ={
createProduct : function(){
    console.log('The method has been overwriten successfully');
},
init : function(config){
    console.log("Start my object")
    if(typeof config.createProduct === "function"){
        this.createProduct = config.createProduct;
    }
}
}
var myConfig = {
createProduct : function(){
    throw new Error("The createProduct() method has not been implemented.");
}   
}
var factory = new AbstractFactory(myConfig);
factory.createProduct()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.