是否可以动态附加到对象实例的原型?例如,我有两个dell对象,一个是笔记本电脑,另一个是桌面。我希望能够创建两个dell实例,然后将原型扩展到笔记本电脑或台式机,这样我就可以使用适当的getter / setter。
JSFiddle链接: http://jsfiddle.net/QqXgV/1/
var dell = function(){}
dell.prototype = new computer();
dell.prototype.constructor = dell;
var hp = function(){}
hp.prototype = new computer();
hp.prototype.constructor = hp;
var computer = function(){}
computer.prototype.setType = function(type){
//Here is where I would extend.
this.prototype extends window[type].prototype;
}
var laptop = function(){}
laptop.prototype.getKeyboard = function(){
return "motherboard";
}
var desktop = function(){}
desktop.prototype.getKeyboard = function(){
return "usb";
}
var dellDesktop = new dell();
dellDesktop.setType("desktop");
var dellLaptop = new dell();
dellLaptop.setType("laptop");
//This is the end goal.
dellDesktop.getKeyboard(); //Returns usb
dellLaptop.getKeyboard(); //Returns motherboard
//And then be able to do the same thing with hp.
答案 0 :(得分:1)
如果戴尔可以是笔记本电脑或台式机,则可以创建DellLaptop和DellDesktop构造函数。但笔记本电脑配备超极本和上网本,因此必须创建DellLaptopUltrabook和DellLaptopNetBook。因此,如果某些东西可以是这个或那个,而其他对象可以是这个或那个(如HP也可以是笔记本电脑或桌面),也许以下模式可以提供帮助:
var Computer = function(){};
//proxy getKeyboard based on what type it is
Computer.prototype.getKeyboard = function(){
return this.type.getKeyboard.call(this);
};
var Dell = function(args){
//do some checks on args here
//re use Computer constructor
Computer.call(this.args);
//re use laptop or Desktop constructor code
args.type.call(this,args);
//re use Laptop or Desktop protype members
this.type=args.type.prototype;
};
Dell.prototype = Object.create(Computer.prototype);
Dell.prototype.constructor = Dell;
var Laptop = function(){};
Laptop.prototype.getKeyboard = function(){
return "motherboard";
};
//ultrabook and netbook can inherit from Laptop
// so you could pass UltraBook or Netbook as type
var Desktop = function(){};
Desktop.prototype.getKeyboard = function(){
return "usb";
};
var dellDesktop = new Dell({type:Desktop});
var dellLaptop = new Dell({type:Laptop});
//This is the end goal.
console.log(dellDesktop.getKeyboard()); //Returns usb
console.log(dellLaptop.getKeyboard()); //Returns motherboard