其它方式:工厂方式,构造函数方式,原型方式都各有各的大缺陷,这里就不一一介绍了,想了解的可以去看一下这本著作的第3章节。
1. 混合构造函数/原型方式
- 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);
- };
- var ocar1 = new car(“red”, 4 , 23 );
- var ocar2 = new car(“blue”, 3 , 25 );
- ocar1.drivers.push(“matt”);
- alert(ocar1.drivers); // outputs “mike,sue,matt”
- alert(ocar2.drivers); // outputs “mike,sue”
优点:具有其它方式的优点而没有其它方式的缺点
不足:封装性欠缺
2 . 动态原型方式
- 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 ;
- }
- }
优点:封装性比上一个方式更好
不足:就是看上去奇怪一点,呵呵
总之,以上2种方式是目前最广泛使用的,尽量使用它们避免不必要的问题。
闽公网安备 35060202000074号