javascript复习笔记六----面向对象程序设计(继承)

这篇博客详细介绍了JavaScript中的面向对象程序设计,涵盖了从基本原型链到寄生组合式继承的多种继承模式,包括构造函数借用、组合继承、原型式继承、寄生式继承等核心概念,特别强调了寄生组合式继承作为引用类型最理想的继承方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承

1.基本原型链

function SuperType(){

this.property = true;

}

SuperType.prototype.getSuperValue = function(){

return this.property;

};

function SubType(){

this.subproperty = false;

}

//继承了SuperType

SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function (){

return this.subproperty;

};

var instance = new SubType();

alert(instance.getSuperValue()); //true


 

 

 

2.借用构造函数

function SuperType(){

this.colors = ["red", "blue", "green"];

}

function SubType(){

//继承了SuperType

SuperType.call(this);

}

var instance1 = new SubType();

instance1.colors.push("black");

alert(instance1.colors); //"red,blue,green,black"

var instance2 = new SubType();

alert(instance2.colors); //"red,blue,green"


   

3.组合继承(最常用的继承模式)

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);

this.age = age;

}

//继承方法

SubType.prototype = new SuperType();

SubType.prototype.constructor = SubType;

SubType.prototype.sayAge = function(){

alert(this.age);

};

var instance1 = new SubType("Nicholas", 29);

instance1.colors.push("black");

alert(instance1.colors); //"red,blue,green,black"

instance1.sayName(); //"Nicholas";

instance1.sayAge(); //29

var instance2 = new SubType("Greg", 27);

alert(instance2.colors); //"red,blue,green"

instance2.sayName(); //"Greg";

instance2.sayAge(); //27


 

 

4.原型式继承

function object(o){

function F(){}

F.prototype = o;

return new F();

}

 

或则:ECMAScript 5  Object.create()方法

 

 

5.寄生式继承

function createAnother(original){

var clone = object(original); //通过调用函数创建一个新对象

clone.sayHi = function(){ //以某种方式来增强这个对象

alert("hi");

};

return clone; //返回这个对象

}


 

 

6.寄生组合式继承(是引用类型最理想的继承范式)

function inheritPrototype(subType, superType){

var prototype = object(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);

this.age = age;

}

inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function(){

alert(this.age);

};

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值