前提说明:个人自学随笔,若有兴趣可供读者了解
<!doctype html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script type="text/javascript">
//交流现象:当原型属性与本地属性同名时所产生的现象,可为对象初始化默认值
//注意:当二者同名时本地属性会覆盖原型属性的“值”
function p(x)
{
if(x)
{
this.x=x;
}
}
p.prototype.x=1; //利用原型为对象设置默认值(交流现象)
var p1=new p();
document.write(p1.x+"</br>"); //结果为1,设置默认值成功
var p2=new p(10);
document.write(p2.x+"</br>"); //结果为10,为本地属性赋值后,覆盖原型属性的值。
document.write("<hr/>");
//利用原型间接为实现本地数据备份
function f(x)
{
this.x=x;
}
f.prototype.backup=function()
{
for(var i in this)
{
f.prototype[i]=this[i];
}
}
var f1=new f(100);
f1.backup();
f1.x=0;
document.write(f1.x+"</br>");
f1=f.prototype;
document.write(f1.x+"</br>");
document.write("<hr/>");
//利用原型提高对象内部安全性,为对象属性设置“只读”(如为原型对象设计闭包,阻断对象直接联系)特性
function fun( x, y)
{
this.x=x;
this.y=y;
fun.prototype.x=0;
fun.prototype.y=0;
}
function L(a,b)
{
var a=a;
var b=b;
var w=function()
{
return Math.abs(a.x-b.x);
}
var h=function()
{
return Math.abs(a.y-b.y);
}
this.length=function()
{
return (Math.sqrt(w()*w()+h()*h()).toFixed(3))
}
this.bean=function()
{
function temp(){}; //构造临时类
temp.protopyte=a; //把私有对象传递给临时原型对象
return new temp(); //返回实例化对象,阻断方法bean()对私有对象a的影响,防止通过调用bean()引用私有属性a.
}
this.end=function()
{
function temp(){};
temp.prototype=b;
return new temp();
}
}
var a=new fun(1,2);
var b=new fun(10,20);
var lgh=new L(a,b);
document.write(lgh.length()+"</br>");
lgh.bean().x=50; //改变方法bean()的一个属性为50
document.write(lgh.length()+"</br>"); //结果未变,说明通过原型对象完好的阻断了方法对私有对象的影响
document.write("<hr/>");
//利用原型进行批量复制
function fun1(x)
{
this.x=x;
}
var a=[];
function temp(){};
temp.prototype=new fun1(10);
for(var i=0;i<10;i++)
{
a[i]=new temp(); //数组存的是实例对象,而非单纯的数值
}
document.write(a[0].x+"</br>");
temp.prototype.x=20; //修改原型对象属性即可修改全部数组中储存的“值”
document.write(a[0].x+"</br>");
document.write("<hr/>");
</script>
</body>
</html>