许多权威的javascript书上说“
原型链(prototype chaining)方式继承,
与对象冒充相似,子类的所有属性和方法都必须出现在 prototype 属性被赋值后,
因为在它之前赋值的所有方法都会被删除。为什么?因为 prototype 属性被替换成了新对象,
添加了新方法的原始对象将被销毁。”
但是混合方式的继承就是反例。
看了书上说的是不对的吧?
一下是我自己测试的例子,在IE8,opera10,chrome10下都通过了。
[code="java"]
function ClassA() { } ClassA.prototype.color = "blue"; ClassA.prototype.sayColor = function () { alert(this.color); }; function ClassB() { this.name = 'this_name'; this.sayName = function () { alert(this.name); }; } ClassB.prototype = new ClassA(); //ClassB.prototype.name = ""; //ClassB.prototype.sayName = function () { //alert(this.name); //}; var objA = new ClassA(); var objB = new ClassB(); objA.color = "blue"; objB.color = "red"; //objB.name = "John"; objA.sayColor();//this_name objB.sayColor(); objB.sayName();
[/code]
书上说的是给prototype赋值,即:
F.prototype = {}
这种操作是不影响已经创建出来的对象实例的
而如果是修改当前prototype对象的属性,就会有影响,因为它们是引用的同一对象:
F.prototype.a = xxx