javascript 类定义的4种方法
2009-09-12 00:00
495 查看
/* 工厂方式--- 创建并返回特定类型的对象的 工厂函数 ( 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 类定义4种方法
- javascript 类定义的4种方法
- JavaScript数据结构之广义表的定义与表示方法详解
- JavaScript定义及输出螺旋矩阵的方法详解
- JavaScript 实现的4种数字千位符格式化方法
- Javascript定义类(class)的三种方法
- JavaScript通过function定义对象并给对象添加toString()方法实例分析
- javascript中定义类的方法详解
- Javascript定义类(class)的三种方法--(转载)原作者阮一峰
- javascript中希望定义一个页面刷新也不能改变其值的方法
- 讨论javascript(一)工厂方式 js面象对象的定义方法
- 【 javascript 】.match()方法定义
- javascript数组的定义及其属性和方法的使用
- 在Silverlight1.1中定义与调用Javascript事件的方法
- javascript 在 构造器函数中定义方法 vs 在 prototype 中定义方法
- Javascript教程:js异步编程的4种方法详述(转载)
- javascript中定义类的方法汇总
- Javascript 两种定义Function的方法
- javascript 类方法定义还是有点区别