zoukankan      html  css  js  c++  java
  • javascript定义类的几种方法

    javascript定义类的几种方法。

      /*

      工厂方式--- 创建并返回特定类型的对象的 工厂函数 ( factory function )

      */ 

    function createCar(color,doors,mpg){  
       var tempCar = new Object;  
       tempCar.color = color;  
       tempCar.doors = doors;  
       tempCar.mpg = mpg;  
       tempCar.showCar = function(){  
         alert(this.color + " " + this.doors);  
       }  
      return tempCar;  
    } 

      /*

      构造函数方式--- 构造函数看起来很像工厂函数

      */ 

    function Car(color,doors,mpg){  
      this.color = color;  
      this.doors = doors;  
      this.mpg = mpg;  
      this.showCar = function(){  
         alert(this.color);  
       };  
    } 

      /*

      原型方式--- 利用了对象的 prototype 属性,可把它看成创建新对象所依赖的原型

      */ 

    function Car(color,doors,mpg){  
      this.color = color;  
      this.doors = doors;  
      this.mpg = mpg;  
      this.drivers = new Array("nomad","angel");  
    }  
    Car.prototype.showCar3 = function(){  
       alert(this.color);  
    };

      /*

      混合的构造函数 /原型方式--- 用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法)

      */ 

    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);  
    }; 

      /*

      动态原型方法--- 在构造函数内定义非函数属性,而函数属性则利用原型属性定义。唯一的区别是赋予对象方法的位置。

      */ 

    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;  
       }  
    }

      //该方法使用标志( _initialized )来判断是否已给原型赋予了任何方法。  

      利用原型prototype。

    function Bar(text, url) {
    this.text = text;
    this.url = url;
    }
    Bar.prototype = {
    render : function() {
    document.write('<a href="' + this.url + '">' + this.text + '</a>');
    }
    }

  • 相关阅读:
    【Android】升级ADT 22 引发的错误
    【Android】使用SearchView时软键盘不支持actionSearch的问题
    Mac 升级 OS X 10.8.2 后 VirtualBox 无法启动的问题
    2012年总结
    【Andorid X 项目笔记】魅族照片剪切问题(4)
    【读书笔记】浪潮之巅
    ormlite更改数据库默认位置
    Android实用代码七段(二)
    Android实用代码七段(三)
    【Android】嵌套Fragment无法接收onCreateOptionsMenu事件的问题
  • 原文地址:https://www.cnblogs.com/cxd4321/p/1614062.html
Copyright © 2011-2022 走看看