JavaScript - 创建类的方法

/*工厂模式*/
    function createCar(){
        var car  =  new Object();
        car.color="b";
        car.length=1;
        car.run = function(){
            console.log("run");
        }
        return car;
    }
    var car1_1  =  createCar();
    car1_1.run();
    var car2_2  =  createCar();
    /*这种方式的问题是每一次创建一个car对象,run Function也都必须重新创建一次.浪费内存*/

    /*构造方法式*/
    function Student(name,age){
        this.name = name;
        this.age = age;
        this.add = function(){
            console.log(this.name + this.age);
        }
    }
    var stu1 = new Student('Gao','77');
    stu1.add();
    /*这是最基本的方式,但是也存在和factory方式一样的毛病*/

    /*prototype方式*/
    function P_Car(){

    }
    P_Car.prototype.color="b";
    P_Car.prototype.length=1;
    P_Car.prototype.run=function(){
        console.log("run");
    };

    P_Car.prototype.data1=new Array();
    var pcar1=new P_Car();
    var pcar2=new P_Car();
    pcar1.data1.push("a");
    /*此时,car2.data也就包含了"a"元素*/

    /*Prototype/Constructor杂合方式*/
    function M_Car(){
        this.color="b";
        this.length=1;
        this.data2 = new Array();
    }

    M_Car.prototype.run=function(){
        console.log("dddd");
    };

    var m_car1 = new M_Car();
    m_car1.data2.push(m_car1.color,m_car1.length);
    console.log(m_car1.data2);
    /*这种方式去除了那些缺点.是目前比较大范围使用的方式*/

   /* 动态prototype方式*/
    function auto_Car(){
        this.color="b";
        this.length=1;
        this.data1 = new Array();

        if(typeof auto_Car.initilize=="undefined"){
            auto_Car.prototype.run = function(){
                alert("adsa");
            }
        }

        auto_Car.initilize=true;
    }
    var auto_car = new auto_Car();
    auto_car.run();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值