定义类和对象

如何利用JS创建自定义的类和对象?

1.  工厂的方式

<script language="JavaScript">

  function createCar(color, mpg) {

       var car = new Object();

       car.color = color;

       car.mpg = mpg;

       car.showCar = function () {

                alert(this.color);

                alert(this.mpg);

       };

       return car;

  }

  var car = createCar("red", 23);

  car.showCar();

</script>

以上方法:每次createCar都要创建新函数showCar,每个对象都有自己的showCar,实际上每个对象可以共享showCar函数

<script language="JavaScript">

  function createCar(color, mpg) {

       var car = new Object();

       car.color = color;

       car.mpg = mpg;

       car.showCar = showCar;

       return car;

  }

  function showCar() {

       alert("");

       alert(this.color);

       alert(this.mpg);

  }

  var car = createCar("red", 23);

  car.showCar();

</script>

以上方法:解决了重复创建函数问题,但是这个函数不像是对象特有的方法

2.  构造函数方法

<script language="JavaScript">

  function Car(color, mpg) {

       this.color = color;

       this.mpg = mpg;

       this.showCar = showCar;

  }

  function showCar() {

       alert("Car");

       alert(this.color);

       alert(this.mpg);

  } 

  var car = new Car("red", 23);

  car.showCar();

</script>

以上方法:和工厂方法一样,都会产生重复定义函数,以及函数不像是对象特有的方法的问题

3.  混合构造函数/原型方法

<script language="JavaScript">

  function Car(color, mpg) {

       this.color = color;

       this.mpg = mpg;

  }

         Car.prototype.setColor = function (color) {

                   this.color = color

         }

         Car.prototype.showCar = function () {

       alert("prototype");

       alert(this.color);

       alert(this.mpg);

  } 

  var car = new Car("red", 23);

  car.showCar();

  car.setColor("blue");

  car.showCar();

</script>

以上方法:利用对象的prototype属性,将所有属性和方法直接赋予对象的prototype属性,每个Car实例存放的都是指向showColor函数的指针。

4.  动态原型方法

<script language="JavaScript">

  function Car(color, mpg) {

       this.color = color;

       this.mpg = mpg;

      

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

                Car.prototype.showCar = function () {

                          alert("prototype");

                          alert(this.color);

                          alert(this.mpg);

                };

                Car._initialized = true;

           }

  }

  var car = new Car("red", 23);

  car.showCar();

</script>

以上方法:利用_initialized做标志位,来判断是否给原型赋予了任何方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值