在JavaScript中使用prototype對象擴(kuò)展對象屬性和方法
JavaScript是基于對象的程序開發(fā)語言,在JavaScript中可以創(chuàng)建對象和函數(shù),但創(chuàng)建好了的對象在需要時(shí)也可以使用prototype對象對其屬性和方法進(jìn)行擴(kuò)展。
1. 定義一個(gè)對象
function person(name,age,sex){
?this.name=name;
?this.age=age;
?this.sex=sex;
?this.display=display;
}
2. 對象中的一個(gè)方法實(shí)現(xiàn)
function display(){
?var str="Person: \n";
?if(this.name != null)
??str+="name: "+this.name+"\n";
?if(this.age != null)
??str+="age: "+this.age+"\n";
?if(this.sex != null)
??str+="sex: "+this.sex+"\n";
?alert(str);
}
3. 利用prototype對對象的屬性進(jìn)行擴(kuò)展
person.prototype.address="BeiJing Road";
4. 利用prototype對對象的方法進(jìn)行擴(kuò)展
person.prototype.showInfo=function(){
?var str="Person: \n";
?if(this.name != null)
??str+="name: "+this.name+"\n";
?if(this.age != null)
??str+="age: "+this.age+"\n";
?if(this.sex != null)
??str+="sex: "+this.sex+"\n";
?if(this.address != null)
??str+="address: "+this.address+"\n";
?alert(str);
}
5. 使用:
var man= new person("Jack",20);
man.display();
man.showInfo();
6.擴(kuò)展window方法,不用加prototype
<html>
<head>
<title>無標(biāo)題文檔</title>
<script language="javascript">
?<!--
?function fullScreen(){
?window.moveTo(0,0);
?window.outerWidth=screen.width;
?window.outerHeight=screen.height;
}
window.maximize=fullScreen;
?//-->
</script>
</head>
<body>
<form>
?<input type="button" value="click me" onClick="window.maximize();">
</form>
</body>
</html>