通过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>