• 《JavaScript高级程序设计》阅读笔记(十三):定义类或对象


    工厂方式

      创建并返回特定类型的对象。  

    function createCar(sColor,iDoors,iMpg){
    var oTempCar=new Object();
    oTempCar.color=sColor;
    oTempCar.doors=iDoors;
    oTempCar.mpg=iMpg;
    oTempCar.showColor=function(){
    alert(this.color);
    }
    return oTempCar;
    }

      调用示例:

    var oCar1=createCar("red",4,23);
    var oCar2=createCar("blue",3,25);
    oCar1.showColor();
    oCar2.showColor();

      缺点:方法重复创建了。如在上面的调用示例中,oCar1和oCar2均有自己的shoColor方法,但这个是可以共用的。

    构造函数方式

      示例:

    function Car(sColor,iDoors,iMpg){
    this.color=sColor;
    this.door=iDoors;
    this.mpg=iMpg;
    this.showColor=function(){
    alert(this.color);
    }
    }

      调用示例:

    var oCar1=new Car("red",4,23);
    var oCar2=new Car("blue",3,25);

      缺点:跟工厂方式一样,方法重复创建了。

    原型方式

      本方式利用了对象的 prototype 属性,可把它看成创建新对象所依赖的原型。这里用空构造函数来设置类名,然后所有的属性和方法都被直接赋予 prototype 属性,重写前面的例子,代码如下:

    function Car(){
    }

    Car.prototype.color="red";
    Car.prototype.doors=4;
    Car.prototype.mpg=23;
    Car.prototype.showColor=function(){
    alert(this.color);
    }

      调用:

    var oCar1=new Car();
    var oCar2=new Car();

      缺点:不能通过给构造函数传递参数初始化属性的值

    混合的构造函数/原型方式

      联合使用构造函数和原型方式,示例如下:

    function Car(sColor,iDoors,iMpg){
    this.color=sColor;
    this.door=iDoors;
    this.mpg=iMpg;
    }

    Car.prototype.showColor=function(){
    alert(this.color);
    }

      调用示例:

    var oCar1=new Car("red",4,23);
    var oCar2=new Car("blue",3,25);

      优点:无内存浪费,创建方便。

      这种方式是ECMAScript采用的主要方式。

    动态原型方法

      使用混合的构造函数/原型方式把对象的方法放在了对象外面定义,让人感觉不是那么面向对象,没有在视觉上进行很好的封装,因此产生了动态原型方法:

    function Car(sColor,iDoors,iMpg){
    this.color=sColor;
    this.door=iDoors;
    this.mpg=iMpg;
    if(typeof Car._initialized=="undefined"){
    Car.prototype.showColor=function(){
    alert(this.color);
    };
    Car._initialized=true;
    }
    }
  • 相关阅读:
    ubuntu 软件包(package)更换源(source)为阿里云镜像 update&upgrade
    【转载】 ftp 命令行
    阿里云服务器开启端口
    [转载] login shell和non-login shell
    python中global变量释疑
    python 用abc模块构建抽象基类Abstract Base Classes
    【转载】python 特殊函数 dunder function
    tensorflow2.0——波士顿房价数据与多个特征的关系(多元函数的预测)
    tensorflow2.0——波士顿房价数据与房间数关系的预测
    tensorflow2.0——自动求导GradientTape
  • 原文地址:https://www.cnblogs.com/artwl/p/2426082.html
Copyright © 2020-2023  润新知