1.最常见的原型使用示例,就不仔细讲解了:
<html>
<body>
<script type="text/javascript">
function Car (desc) {
this.desc = desc;
this.color = "red";
}
Car.prototype = {
getInfo: function() {
return 'A ' + this.color + ' ' + this.desc + '.';
}
};
//instantiate object using the constructor function
var car = Object.create(Car.prototype);
car.color = "blue";
alert(car.getInfo());
</script>
</body>
</html>
2.原型的升华:inherit的使用(狠明显的功效:防止篡改原型数据。)。讲解见代码。
<!DOCTYPE html>
<html>
<body>
<h1>我的第一段 JavaScript</h1>
<p id="demo">
JavaScript 能改变 HTML 元素的内容。
</p>
<script type="text/javascript">
function myFunction()
{
var unitcircle={r:1};
var c=inherit(unitcircle);//c继承属性r
c.x=1;c.y=1;//c定义两个属性。
c.r=2;
alert("unitcircle.r:"+unitcircle.r);//输出为 1
alert("c.r:"+c.r);//输出为 2
}
function inherit(p){
if(p==null) throw TypeError();//p是一个对象,但不能是空
if(Object.create)//判断Object.create方法是否存在。
return Object.create(p);
var t = typeof p;//如果不存在,继续检查。
if(t!=="object" && t!=="function") throw TypeError();
function f(){}; //1定义一个空构造函数。
f.prototype = p;//2-将其原型属性赋值为p
return new f(); //创建p的继承对象。
}
</script>
<button type="button" οnclick="myFunction()">点击这里</button>
</body>
</html>
3.未完待续。