2013-08-07 60 views
3

在下面的例子中,我预计createProduct函数将被覆盖。但结果是错误。如何用JavaScript中的原型覆盖函数?

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

'工厂'对象具有'createProduct'方法本身,它没有被覆盖。 – Bergi

回答

4

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

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

1

问题是JavaScript中没有抽象这样的东西。你可以实现你想要的一种方法是使用更多的模块化方法。在创建工厂对象时,可以将函数传递到将覆盖createProduct函数的AbstractFactory函数中。

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前检查。

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