javascript学习之面向对象

来源:互联网 发布:java审批流程开源 编辑:程序博客网 时间:2024/06/05 05:01

1.工厂模式

function showColor () {

alert(this.color);

}//保证了这个函数只有一个备份


function createCar() {

var tmpCar = new Object;

tmpCar.color = "red";

tmpCar.name = "fff";

tmpCar.showColor = showColor; 

return tmpCar;

}


var car1 = createCar();

var car2 = createCar();

2.构造函数方式

function Car() {

this.color = 1;

this.name = "f";

}

var car = new Car();

3.原型方式

function Car(){

}

Car.prototype.color = 12;

Car.prototype.drivers = new Array(1,2);


var car1 = new Car();.

var car2 = new Car();

car1.drivers.push(3);

那么就会造成两个car的drivers都会变成1,2,3因为两者是共享了一个array的地址的。而且还无法传入构造参数


4.混合构造函数与原型方式

利用构造函数来构造属性 利用原型来构造共享函数

function Car(参数) {

this.color = xxx;

this.name = xxx;

}

Car.prototype.show = function () {

xxxx

}


5.为了取悦oop的传统程序员 有了动态原型方法

function Car() {

this.color = xxx;

this.name = xxx;

this.drivers = new Array(aa, bb);

if(typeof Car.__initialized == "undefined") {

Car.prototype.show = function() {

xxxxxs

}

}