function createAnother(original){ var clone = Object.create(original); //通过调用函数创建一个新对象 clone.sayHi = function(){//以某种方式来增强这个对象alert("Hi"); };return clone;//返回这个对象}var person = { name: "Bob", friends: ["Shelby", "Court", "Van"]};var anotherPerson = createAnother(person);anotherPerson.sayHi();在上述例子中,createAnother函数接收了一个参数,也就是将要作为新对象基础的对象。
function SuperType(name){ this.name = name; this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function(){ alert(this.name);}function SubType(name, age){ SuperType.call(this, name); //第二次调用SuperType()this.age = age;}SubType.prototype = new SuperType(); //第一次调用SuperType()SubType.prototype.sayAge = function(){ alert(this.age);}
在第一次调用SuperType构造函数时,SubType.prototype会得到两个属性: name和colors; 他们都是SuperType的实例属性,只不过现在位于SubType的原型中。
当调用SubType构造函数时,又会调用一次SuperType构造函数,这一次又在新对象上创建了实例属性name和colors。
于是这两个属性就屏蔽了原型中的两个同名属性。
寄生组合式继承就是为了解决这一问题。
通过借用构造函数来继承属性;
通过原型链来继承方法。
不必为了指定子类型的原型而调用超类型的构造函数,
function inheritPrototype(subType, superType){ var protoType = Object.create(superType.prototype); //创建对象 protoType.constructor = subType; //增强对象 subType.prototype = protoType;//指定对象}function SuperType(name){ this.name = name; this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function(){ alert(this.name);}function SubType(name, age){ SuperType.call(this, name); //第二次调用SuperType()this.age = age;}inheritPrototype(SubType, SuperType)SubType.prototype.sayAge = function(){ alert(this.age);}var instance = new SubType("Bob", 18);instance.sayName();instance.sayAge();inheritPrototype函数接收两个参数:子类型构造函数和超类型构造函数。