免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 963 | 回复: 0
打印 上一主题 下一主题

创建对象 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-20 09:48 |只看该作者 |倒序浏览
一.定义对象
第一步:创建一个函数来构造新的对象
例:
命名对象是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对象都可以使用该方法来.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP