1、混合的构造函数/原型方法
用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法),结果所有函数都只创建一次,而每个对象都具有自己的对象属性实例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>混合的构造函数/原型方法</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
}
Car.prototype.show = function() {
alert(this.color + " " + this.doors + " " + this.mpg + " " + this.drivers.toString());
}
function test() {
var oCar1 = new Car("red", 4, 23);
var oCar2 = new Car("blue", 3, 25);
oCar2.drivers.push("Tom");
oCar2.drivers.shift();
oCar2.drivers.unshift("Jim");
oCar1.show(); //输出:red 4 23 Mike,Sue
oCar2.show(); //输出:blue 3 25 Jim,Sue,Tom
}
</script>
</head>
<body>
<input type="button" οnclick="test()" value="确定"/>
</body>
</html>
2、动态原型方法
动态原型方法的基本想法与混合的构造函数/原型方式相同,即在构造函数内定义非函数属性,而函数属性则利用原型属性定义。唯一的区别是赋予对象方法的位置,动态原型方法提供更友好的编码风格。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>动态原型方法</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
if(typeof Car._initialized == "undefined") {
Car.prototype.show = function() {
alert(this.color + " " + this.doors + " " + this.mpg + " " +
this.drivers.toString());
}
}
}
function test() {
var oCar1 = new Car("red", 4, 23);
var oCar2 = new Car("blue", 3, 25);
oCar2.drivers.push("Tom");
oCar2.drivers.shift();
oCar2.drivers.unshift("Jim");
oCar1.show(); //输出:red 4 23 Mike,Sue
oCar2.show(); //输出:blue 3 25 Jim,Sue,Tom
}
</script>
</head>
<body>
<input type="button" οnclick="test()" value="确定"/>
</body>
</html>
JavaScript高级程序设计学习笔记4: 创建对象
最新推荐文章于 2024-09-05 12:17:13 发布