通過new運算符創建JavaScript內置對象:
var obj = new Object();
通過new運算符創建自定義類型對象:
function Employee(empno,ename){
this.empno = empno;
this.ename = ename;
}
var yuangong = new Employee(7369,”SMITH”);
通過new運算符創建自定義類型對象,并且給“該對象”動態擴展屬性
yuangong.sal = 800; //sal屬性只對當前yuangong對象有效。
通過new運算符創建自定義類型對象,給“該類型(作用到所有對象上)”動態擴展屬性
Employee.prototype.comm = null;
yuangong.comm = 100;
通過new運算符創建自定義類型對象,給“該類型(作用到所有對象上)”動態擴展方法
Employee.prototype.work = function(){
document.write(this.ename + “ is working!”);
}
yuangong.work();
示例:new 操作符號,動態的操作對象
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>無標題文檔</title>
<script language="javascript">
function Emp(empno,ename){
this.empno = empno;
this.ename = ename;
}
var e1 = new Emp(7982,"張三");
e1.comm = 2000; // comm屬性只對e1這個對象生效
alert(e1.empno + "" + e1.ename + " " + e1.comm);
// 給Emp類動態的添加了一個sal屬性
Emp.prototype.sal = null;
e1.sal = 4000;
alert(e1.empno + "" + e1.ename + " " + e1.comm + " " + e1.sal);
// 給Emp類動態的添加了一個work()方法
Emp.prototype.work = function(){
return this.ename +" 在工作";
}
alert(e1.work());
</script>
</head>
<body>
</body>
</html>
自定義類型中的屬性是另一種自定義類型
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>無標題文檔</title>
<script language="javascript">
function Person(age,name){
this.name = name;
this.age = age;
}
function Car(color,owner){
this.color = color;
this.owner = owner;
}
var per = new Person(21,"張1");
var car = new Car("白色",per);
// 訪問所有者的名字屬性
alert(car.owner.name);
</script>
</head>
<body>
</body>
</html>