javascript之父道格拉斯在2006年给出了这样一串代码,来实现继承.
1 function object(o) { 2 function F() { } 3 F.prototype = o; 4 return new F(); 5 }
下面来看看这个函数是如何实现继承的.
1 var Human = { 2 name: "guo", 3 colors: ["red","black"] 4 } 5 var one = object(Human); 6 one.colors.push("yellow"); 7 8 var two = object(Human); 9 two.colors.push("green"); 10 11 alert(two.colors); //red,black,yellow,green
在ECMAScript5中,这个方法得到了封装.Object.create();
1 var Human = { 2 name: "guo", 3 colors: ["red", "black"] 4 } 5 var one = Object.create(Human); 6 one.colors.push("yellow"); 7 var two = Object.create(Human); 8 two.colors.push("green"); 9 alert(two.colors);// red,black,yellow,green