一.定义对象第一步:创建一个函数来构造新的对象
例: 命名对象是Card对象,每个对象都有下面的属性: --- name(姓名) --- addres(地址) --- workphone(办公电话) --- homephone(家庭电话)
Card对象的构造函数
funtion Card(name,address,work,home){
this.name = name;
this.address = address;
this.workphone = work;
this.homephone = home;
this.PrictCard = PrictCard;//定义方法引用函数
}
|
二.定义对象的方法(就是定义一个函数)
读取当前对象(this)的属性
function PrictCard(){
line1 = "Name:"+this.name+"<br>\n";
line2 = "Address:"+this.address+"<br>\n";
line3 = "Work Phone:"+this.workphone+"<br>/n";
line4 = "Home Phone:"+this.homephone+"<br>/n";
document.write(line1,line2,line3,line4,"/n");
}
|
三.创建对象实例(用new关键字)
tom = new.Card("Tom Jones","123 Elm Street","555-1236","555-9876"); tom.PrintCard();执行方法
或
holmes = new.Card();
holmes.name = "Sherlock Holmes";
holmes.address = "221B Baker Street";
holmes.workphone = "555-1365";
holmes.homephone = "555-5454";
holmes.Printcard();
|
扩展内置对象(扩展内置对象定义的功能,添加新的属性与方法)(使用prototype关键字,可以对现有的对象添加属性与方法)
例:向String对象定义添加一个方法 创建新的名字heading的方法,将字符串转为HTML标题.
title = "Fred's Home Page";
下面语句将title字符串内容,作为HTML第一级标题: documnet.write(title.heading(1));
向String对象添加方法具体如下:
<html>
<head><title>Test of heading method</title>
</head>
<body>
<script Langage="JavaScript" type="text/Javascript">
function addhead(level){
html = "H"+level;
text = this.toString();
start = "<"+html+">";
stop = "</"+html+">";
return start+text+stop
}
String.prototype.heading = addead;
document.write("This is a heading 1".heading(1));
document.write("This is a heading 2".heading(2));
document.write("This is a heading 3".heading(3));
</script>
</body>
</html>
|
定义 addhead()方法,作为新的字符串方法,定义函数后.使用prototype关键字将它添加为String对象的方法,然后,任何String对象都可以使用该方法来. |