javascript面向对象 代码详解(七)

//原型式继承

//临时中转函数
function obj(o)           //o表示将要传递进去的一个对象
{
	function F(){}         //F构造是一个临时新建的对象,用来存储传递过来的对象
	F.prototype = o;    //将o对象的实例赋值给F构造的原型对象
	return new F();      //最后返回这个传递过来的对象的对象实例
	
}
//F.prototype = o 其实就相当于 Desk.prototype = new Box();

// 这是字面量的声明方式 ,相当于var box = new Box();
var box = 
{
	name : "Lee",
	age : 100,
	family : ["哥哥","姐姐","妹妹"]
};

//box1就等于new F()
var box1 = obj(box);
alert(box1.family);
box1.family.push("弟弟");
alert(box1.family);


var box2 = obj(box)
//引用类型的属性共享了
alert(box2.family);


//寄生式继承 (原型式+工厂模式)

//临时中转函数
function obj(o)           
{
	function F(){}         
	F.prototype = o;    
	return new F();      
	
}

//寄生函数
function create(o)
{
	var f  = obj(o);
	
	//方便扩展
	f.run = function()
	{
		return this.name + "方法";
	}
	
	return f;
}

var box = 
{
	name : "Lee",
	age : 100,
	family : ["哥哥","姐姐","妹妹"]
};

var box1 = create(box);
alert(box1.name);
alert(box1.run());


//寄生组合继承(雅虎框架)

//临时中转函数
function obj(o)           
{
	function F(){}         
	//相当于F.prototype = Box.prototype
	//单纯的把Box的原型复制过来
	F.prototype = o;    
	return new F();      
	
}

//寄生函数
function create(box,desk)
{
	//F的原型是Box的原型
	//Desk的原型是f
	//相当于 f = new Box() 
	var f  = obj(box.prototype);
	//调整原型构造指针
	f.constructor = desk;
	desk.prototype = f;
}

function Box(name,age)
{
	this.name = name;
	this.age = age;
}

//方法放在原型,每次实例化的时候地址保持一致
Box.prototype.run = function()
{
	return this.name + this.age + "运行中...";
}

function Desk(name,age)
{
	//对象冒充
	//用Desk冒充Box
	Box.call(this,name,age);
}
//通过寄生组合继承来实现继承
create(Box,Desk)           //这句话用来替代Desk.prototype = new Box();

var desk = new Desk("Lee",100); 
alert(desk.run());
alert(desk.constructor);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值