复制代码 代码如下: /* 工厂方式--- 创建并返回特定类型的对象的 工厂函数 ( factory function ) */ function createCar(color,doors,mpg){ var tempCar = new Object; tempCar.color = color; tempCar.doors = doors; tempCar.mpg = mpg; tempCar.showCar = function(){ alert(this.color + " " + this.doors); } return tempCar; } /* 构造函数方式--- 构造函数看起来很像工厂函数 */ function Car(color,doors,mpg){ this.color = color; this.doors = doors; this.mpg = mpg; this.showCar = function(){ alert(this.color); }; } /* 原型方式--- 利用了对象的 prototype 属性,可把它看成创建新对象所依赖的原型 */ function Car(color,doors,mpg){ this.color = color; this.doors = doors; this.mpg = mpg; this.drivers = new Array("nomad","angel"); } Car.prototype.showCar3 = function(){ alert(this.color); }; /* 混合的构造函数 /原型方式--- 用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法) */ function Car(sColor, iDoors, iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike", "Sue"); } Car.prototype.showColor = function () { alert(this.color); }; /* 动态原型方法--- 在构造函数内定义非函数属性,而函数属性则利用原型属性定义。唯一的区别是赋予对象方法的位置。 */ 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.showColor = function () { alert(this.color); }; Car._initialized = true; } } //该方法使用标志( _initialized )来判断是否已给原型赋予了任何方法。
推荐阅读
Javascript 获取滚动条位置等信息的函数
其实这段代码在之前的 “ 用 Javascript 实现锚点(Anchor)间平滑跳转” 一文已经介绍过了,但是由于这个需求并且经常用到,因此,本站专门发布此文介绍,方便查阅。 复制代码 代码如下:<script type="text/javascr>>>详细阅读
本文标题:javascript 类定义的4种方法
地址:http://www.17bianji.com/kaifa2/JS/28159.html
1/2 1