javascript 类定义的4种方法
作者:bea
代码如下: /* 工厂方式--- 创建并返回特定类型的对象的 工厂函数 ( 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
代码如下:
/*
工厂方式--- 创建并返回特定类型的对象的 工厂函数 ( 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 )来判断是否已给原型赋予了任何方法。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- 通过Mootools 1.2来操纵HTML DOM元素
- Mootools 1.2教程 事件处理
- Mootools 1.2教程 函数
- Mootools 1.2教程(3) 数组使用简介
- Mootools 1.2教程(2) DOM选择器
- MooTools 1.2介绍
- IE与Firefox在JavaScript上的7个不同写法小结
- JavaScript 中级笔记 第五章 面向对象的基础
- JavaScript 中级笔记 第四章 闭包
- JavaScript 中级笔记 第三章
- JavaScript 中级笔记 第二章
- JavaScript 中级笔记 第一章
- JavaScript 函数调用规则
- javascript 数组操作实用技巧
- 用JS写的简单的计算器实现代码
- prototype与jquery下Ajax实现的差别
- JS 参数传递的实际应用代码分析
- firefox(火狐)和ie浏览器禁止右键和禁止复制的代码
- javascript类继承机制的原理分析