我的java历程

在JavaScript中使用prototype扩展对象属性和方法

在JavaScript中使用prototype对象扩展对象属性和方法

JavaScript是基于对象的程序开发语言,在JavaScript中可以创建对象和函数,但创建好了的对象在需要时也可以使用prototype对象对其属性和方法进行扩展。

1. 定义一个对象
function person(name,age,sex){
 this.name=name;
 this.age=age;
 this.sex=sex;
 this.display=display;
}

2. 对象中的一个方法实现
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对对象的属性进行扩展
person.prototype.address="BeiJing Road";

4. 利用prototype对对象的方法进行扩展
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.扩展window方法,不用加prototype

<html>
<head>
<title>无标题文档</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>

posted on 2006-12-09 21:13 landril 阅读(1926) 评论(0)  编辑  收藏 所属分类: JavaScript


只有注册用户登录后才能发表评论。


网站导航: