<html>
<head>
<title>javascript中自定义类</title>
<script>
//定义Person类
function Person()
{
}
//创建对象
var p = new Person();
//1、添加属性
p.name = "zhangsan";
p.age = 23;
p.sex = "man";
//通过.访问属性
document.write(p.name + "," + p.age + "," + p.sex + "<br/>");//zhangsan,23,man
//通过[]访问属性
document.write(p["name"] + "," + p["age"] + "," + p["sex"] + "<br/>");
/*
这种方法添加的属性,只是针对某个对象添加的!!
*/
var p2 = new Person();
document.write(p2.name + "," + p2.age + "," + p2.sex + "<br/>");//undefined,undefined,undefined
//2、添加方法
//(1)普通函数
function show()
{
document.write("show():" + p.name + "," + p.age + "," + p.sex + "<br/>");
}
p.start = show;//start和show指向同一个函数体
p.start();
//(2)匿名函数
p.show2 = function() {
document.write("show2():" + p.name + "," + p.age + "," + p.sex + "<br/>");
}
p.show2();
//3、修改属性和方法
p.name = "lisi";//修改属性值
p.show = function () {
document.write("修改后的show() ===>" + p.name + ","+ p.age + "<br/>");
}
p.show();
//4、删除属性和方法
p.name = undefined;//删除属性
p.show();//修改后的show() ===>undefined,23
//p.show = undefined;//删除方法
//p.show();
</script>
</head>
<body>
</body>
</html>
javascript中自定义类(1)
最新推荐文章于 2024-11-02 12:42:04 发布