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();
4

3 回答 3

4

对属性的搜索从对象本身开始,只有在没有找到属性时才检查原型。因此,在“工厂”对象上找到的第一个“createProduct”函数就是错误函数。如果您以其他顺序初始化对象和原型,那么您将得到您期望的结果。

请注意,原型对象上的属性不会导致属性出现在使用构造函数创建的实例对象上。

于 2013-08-07T16:58:16.127 回答
1

问题是 JavaScript 中没有抽象之类的东西。您可以实现所需的一种方法是使用更加模块化的方法。创建工厂对象时,可以将一个函数传递给 AbstractFactory 函数,该函数将覆盖 createProduct 函数。

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

func在将它分配给 createProduct 之前,您可能还想先检查它是一个函数。

于 2013-08-07T17:14:22.027 回答
0

另一个有点帮助的例子:

使用配置覆盖以实现对象。

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()
于 2013-08-07T17:18:35.300 回答