Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中使用原型覆盖函数?_Javascript_Prototype - Fatal编程技术网

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

如何在javascript中使用原型覆盖函数?,javascript,prototype,Javascript,Prototype,在下面的示例中,我希望createProduct函数将被覆盖。但结果是错误的 var AbstractFactory = function(){ this.createProduct = function(){ throw new Error("The createProduct() method has not been implemented."); } } AbstractFactory.prototype.createProduct = function(){ co

在下面的示例中,我希望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();

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


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

问题在于JavaScript中没有抽象这类东西。实现所需功能的一种方法是使用更模块化的方法。创建factory对象时,可以将函数传递到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()

factory
对象本身有
createProduct
方法,您没有覆盖该方法。