HTML开发与应用:利用prototype给函数添加方法。
在书写函数时我们可能会发现之前的函数需要添加一些方法,那么一种方法就是利用prototype,给原先的函数添加新的方法。
下面我们来看一段代码:
function student(){
alert("000");
this.height=1.78;
this.stuName="xiaoming";
this.desc=function(name){
alert("1."+name);
}
}
student.prototype.exam=function(){
alert("2."+this.height);
}
var xiaoming=new student();
xiaoming.desc("hello");
xiaoming.exam();
这里我们可以清晰地知道,添加方法的格式:
要想给某个函数添加方法,那么就是,函数名(student).prototype.添加的方法名(exam)=function()。student.prototype.exam=function()这就相当于在原函数function student()里面加上了个方法。而调用方法也很明确,
var xiaoming=new student();先将xiaoming与student想联系,在这之后,this就指的是xiaoming。
xiaoming.desc(“hello”);
xiaoming.exam(); 这两行我们可以知道添加的方法其实与正常在函数添加方法是划等号的。
也就是说:
this.desc=function(name){
alert("1."+name);}
与这种方法是等价的。
student.prototype.exam=function(){
alert("2."+this.height);}