日期:2014-05-16  浏览次数:20329 次

Js中给对象增加一个原型方法

每个对象都有原型,创建对象时可以选择对象的原型方法。

var stooge = {
	"first-name" : "Jerome",//属性名中如果包含非法的JS标识符或是JS保留字,必须用引号 ,反之可不用引号
	"last-name" : "Howard"
}

??

//每个对象都有原型,创建对象时可以选择对象的原型方法。
//给x增加一个beget方法,这个beget方法创建一个使用原有对象的新对象。
var x = {};
if(typeof x.beget !== 'function'){
	x.beget = function(o){
		var F = function(){}
		F.prototype = o;
		return new F();
	}
}
var another_stooge = x.beget(stooge);//以stooge为原型创建another_stooge对象

??//创建方法供html调用

function prototypeMethod(){
	//原型连接在更新中不起作用,我们对新对象做出改变时,不会像引用一样对原型对象进行修改
	document.getElementById('Prototype1').innerHTML = "修改新对象前属性值:"+another_stooge['first-name']+"  "+stooge['first-name']
	another_stooge['first-name'] = 'Harry';
	document.getElementById('Prototype2').innerHTML = "修改新对象后属性值:"+another_stooge['first-name']+"  "+stooge['first-name']
	delete another_stooge['first-name'];
	document.getElementById('Prototype3').innerHTML = "删除新对象属性后值:"+another_stooge['first-name']+"  "+stooge['first-name']
	//新对象添加属性,不影响原型数据结构
	another_stooge.newValue = 'newValue';
	document.getElementById('Prototype3').innerHTML = "新对象添加属性,不影响原型数据结构:"+another_stooge['newValue']+"  "+stooge['newValue']
	//在原型中添加属性,新对象也能获取到
	stooge.addValue = 'addValue';
	document.getElementById('Prototype4').innerHTML = "在原型中添加属性,新对象也能获取到:"+another_stooge['addValue']+"  "+stooge['addValue']
}
//注:原型是一种动态关系,个人理解 相当于java的继承关系。

?其中HTML中代码为

?

	<input type="button" onclick="prototypeMethod()" value="原型"><br/>
	  	<div id='Prototype1'></div>
	  	<div id='Prototype2'></div>
	  	<div id='Prototype3'></div>
	  	<div id='Prototype4'></div>

?

?

?

?

?

?

?

?

?

?

?

?

?

?