<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>自定义对象</title>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<script language="javascript" type="text/javascript">
/**
* 要创建自己的对象实例,必须首先为其定义一个构造函数。
* 构造函数创建一个新对象,赋予对象属性,并在合适的时候赋予方法。
* 例如,下面的示例为 Person 对象定义了构造函数。
* 注意 this 关键字的使用,它指向当前对象。
*/
/*
function Person(id, name, age){
//Person的Id
this.id = id;
//Person的名字
this.name = name;
//Person的年龄
this.age = age;
}
//定义了对象构造器后,用 new 运算符创建对象实例。
var aPerson = new Person(1, "Kenshin", 24);
//输出aPerson的相应信息
alert(aPerson.name + "的Id:" + aPerson.id + "/n" + aPerson.name + "的年龄:" + aPerson.age);
*/
/*-----------分割线-----------*/
//为了方便查看Person的相关信息,可以在构造器中定义相应的方法
/*
function Person(id, name, age){
//Person的id
this.id = id;
//Person的名字
this.name = name;
//Person的年龄
this.age = age;
// 这里添加 输出Person的信息的方法
// 注意在函数的名称后没有加圆括号;
// 这不是一个函数调用,而是
// 对函数自身的引用。
this.getInformation = getPersonInformation;
}
//实现查看Person信息的方法
function getPersonInformation(){
return (this.name + "的Id为:" + this.id + "/n" + this.name + "的年龄:" + this.age);
}
//使用查看信息的方法
var aPerson = new Person(1, "Kenshin", 24);
alert(aPerson.getInformation);//这里查看的是函数的实现
alert(aPerson.getInformation());//这里才是真正查看aPerson对象的信息
*/
</script>
</head>
<body>
<h1>自定义对象</h1>
</body>
</html>
自定义对象(1)
最新推荐文章于 2024-05-06 18:26:11 发布