1. 创建对象方式:方式一,对象初始化器方式;方式二,构造函数方式;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
//对象初始化器方式
var marry={
name:"marry",
age:2,
shout:function(){
alert("我是:"+this.name+",今年:"+this.age);
},
action:function(){
alert("会吃");
}
};
alert(marry.name);
alert(marry.age);
marry.shout();
marry.action();
//构造函数方式
function Dog(name,age){
this.name=name;
this.age=age;
this.shout=function(){
alert("我是:"+this.name+",今年:"+this.age);
};
this.action=function(){
alert("会吃");
};
}
var jack=new Dog("jack",1);
alert(jack.name);
alert(jack.age);
jack.shout();
jack.action();
</script>
</body>
</html>
2. 对象属性定义:私有属性;对象属性;类属性;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function C(){
this.objPro="对象属性";
C.prototype.objPro2="对象属性2";
var privatePro="私有属性";
}
C.classPro="类属性";
alert(C.classPro);
var c=new C();
alert(c.objPro);
alert(c.objPro2);
</script>
</body>
</html>
上面的私有属性var privatePro="私有属性";要使用闭包的形式才能访问
3. 对象方法定义:私有方法;对象方法;类方法;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
function C(){
var privateFunc=function(){
alert("私有方法");
};
privateFunc(); //私有方法,在new C这个对象的时候会调用
this.objFunc=function(){
alert("对象方法");
};
C.prototype.objFunc2=function(){
alert("对象方法2");
};
}
C.classFunc=function(){
alert("类方法");
};
C.classFunc();
var c=new C();
c.objFunc();
c.objFunc2();
</script>
</body>
</html>