如何在javascript中使用原型覆盖函数

How to overwrite function using prototype in javascript?

本文关键字:原型 覆盖 函数 javascript      更新时间:2023-09-26

在下面的示例中,我希望createProduct函数将被覆盖。但结果是错误。

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

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

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

问题是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之前,您可能还需要先检查它是否是一个函数。

另一个有帮助的例子:

使用配置来实现对象。

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