<script type="text/javascript">
/**
js中创建对象
*/
function my(){
//创建对象
var myobject = {};
myobject.name = "test";
myobject.getName = function(){
return this.name; //需要加this,否则没值
}
alert(myobject.getName());
}
function my2(){
var objecttest = {
name: "aaa",
getName: function(){
return this.name; //需要加this,否则没值
}
}
alert(objecttest.getName());
/*
var a = new objecttest(); 错误因为上面的objecttest是一个具体的对象并不是类,不能new
alert("a.name=" + a.name);
*/
var a = new my();
a.suibian = "suibian";
a.getSu = function(){
return "getsu"
}
alert("添加属性=" + a.suibian);
alert("添加方法=" + a.getSu());
}
//定义方法就相当定义类,我们可以直接new ,构造函数
function ShinyObject(name) {
//都必须要加this
this.name = name;
this.getName = function() {
return this.name;
}
}
function my3() {
var so = new ShinyObject("张三");
alert(so.getName());
//扩张的是对象的本身,而不是类
so.suibian = "suibian";
so.getSu = function() {
return "getsu"
}
alert("so.getSu=" + so.getSu());
/**
var so2 = new ShinyObject("张三");
alert("so2.getSu=" + so2.getSu()); //错 该方法在类中是没有定义的
*/
}
//通过prototype类对类进行扩展
ShinyObject.prototype.sayHello = function() {
return "hello:" + this.name;
};
ShinyObject.prototype.sex="男";
function my4() {
var o = new ShinyObject("张三");
alert("o.sayhello = " + o.sayHello() + "sex=" + o.sex);
}
</script>
</head>
<body>
This is my JSP page. <br>
<input type="button" οnclick="my4()" value="test">
</body>