搜索
写经验 领红包
 > 知识

javascipt继承(js继承的几种方法)

导语:javascript自学记录:继承

6.3 继承

6.3.1 原型链

l 每个构造函数(Person)都有一个原型对象(Person.prototype)

l 原型对象都包含一个指向构造函数的指针(constructor)

l 而实例都包含一个指向原型对象的内部指针(person1.__proto__)

l 那么假如我们让原型对象等于另一个类型的实例(Person.prototype==object1)

l 此时的原型对象将包含一个指向另一个原型的指针(object1.__proto__)

l 相应地,另一个原型中也包含着一个指向另一个构造函数的指针(object1.__proto__.constructor==Object)

l 假如另一个原型又是另一个类型的实例,那么上述关系依然成立。如此层层递进,就构成了实例与原型的链条。

l Object.prototype.__proto__ == null

// 可通过instanceof操作符来确定关系alert(person1 instanceof Person); // truealert(person1 instanceof Object); // truealert(Object.prototype.isPrototypeOf(person1)); // truealert(Person.prototype.isPrototypeOf(person1)); // true

原型链的问题:

多个实例会共享原型属性。

借用构造函数:

function SuperType(){ this.colors = [&34;,&34;,&34;];}function SubType() { SuperType.call(this);}var instance1 = new SubType();instance1.colors.push(&34;);alert(instance1.colors); // red,blue,green,blackvar instance2 = new SuperType();alert(instance2.colors); // red,blue,green,black

在子类构造函数中可以向父类构造函数传递参数,见SuperType.call(this,name):

function SuperType(name){ this.name = name;}function SubType(name) { SuperType.call(this,name); this.age = 38;}var instance1 = new SubType(&34;);alert(instance1.name); // 伍德春alert(instance1.age); // 38

6.3.3 组合继承

function SuperType(name) { this.name = name; this.colors = [&34;,&34;,&34;];}SuperType.prototype.sayName = function () { alert(this.name);};function SubType(name,age) { // 继承属性 SuperType.call(this,name); this.age = age;}// 增加继承的方法SubType.prototype = new SuperType();SubType.prototype.constructor = SubType;SubType.prototype.sayAge = function () { alert(this.age);}var instance1 = new SubType(&34;,38);instance1.colors.push(&34;);alert(instance1.colors); // red,blue,green,blackinstance1.sayName(); // 伍德春instance1.sayAge(); // 38var instance2 = new SubType(&34;,34);alert(instance2.colors); // red,blue,greeninstance2.sayName(); // 李慧instance2.sayAge(); // 34

本文内容由快快网络小婷整理编辑!