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

本文详细介绍了JavaScript中构造函数的基本概念、如何创建对象、对象的实例化过程及对象冒充调用机制。通过实例展示了构造函数的使用方式、构造函数与普通函数的区别,并深入探讨了对象属性和方法的继承性。
//构造函数可用来创建特定的对象
//创建一个对象
function Box(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	this.run = function()
	{
		return this.name + this.age + "运行中...";
	};
}

function Desk(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	this.run = function()
	{
		return this.name + this.age + "运行中...";
	};
}


//1.构造函数没有new Object,但它后台会自动 var obj = new Object
//2.this 相当于obj
//3.构造函数不需要返回对象的引用,它是后台自动返回的


//规范
//1.构造函数也是函数但函数名第一个字母大写
//2.必须new 构造函数名(), new Box(),而这个Box第一个字母也是大写
//3.必须使用new运算符


var box1 = new Box("Lee",100);  //实例化
var box2 = new Box("Jack",200); //实例化
var box3 = new Desk("kkk",500);   //实例化


//解决对象识别问题
//所有构造函数的对象都是object类型
alert(box1 instanceof Object);
//也是box对象
alert(box1 instanceof Box);
alert(box2 instanceof Box);
//可以识别了,因为box3是Desk对象的引用
alert(box3 instanceof Desk);


//对象冒充调用
function Box(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	this.run = function()
	{
		return this.name + this.age + "运行中...";
	};
}

var o = new Object();

//Uncaught TypeError: Object #<Object> has no method 'run' 
//alert(o.run());

//如果想让o.run运行Box.run的方法
//让o冒充Box
//o把Box所有的功能都拿下来了
Box.call(o,"Lee",100);
alert(o.run());


function Box(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	this.run = function()
	{
		return this.name + this.age + "运行中...";
	};
}

var box1 = new Box("Lee",100);  //实例化后地址为1
var box2 = new Box("Lee",100);  //实例化后地址为2

//true 值相等
//alert(box1.name == box2.name);
<pre name="code" class="javascript">function Box(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	
	//说明它是引用类型
	this.run = run;
}

function run()  //把构造函数的内部方法通过全局来实现,引用地址一致
{
	//当普通函数调用run() this代表window
	//当对象调用run()this代表该对象
	return this.name + this.age + "运行中...";
}


var box1 = new Box("Lee",100);  //实例化后地址为1
var box2 = new Box("Lee",500);  //实例化后地址为2

alert(box1.run());
alert(box2.run());

//构造函数体内的方法的值是相等的//true//alert(box1.run() == box2.run());//打印方法的引用地址//因为他们比较的是引用地址//falsealert(box1.run == box2.run);


function Box(name,age)
{
	//添加一个属性
	this.name = name;
	this.age = age;
	//添加一个方法
	
	//说明它是引用类型
	this.run = new Function("return this.name + this.age + '运行中...'")
}

var box1 = new Box("Lee",100);  //实例化后地址为1
var box2 = new Box("Lee",100);  //实例化后地址为2


alert(box1.run());



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值