zoukankan      html  css  js  c++  java
  • Javascript Class

    做个记录,javascript 如何创建类?

    有早期的,有原型的,有构造函数的

    // early javascript object
    var o = {};
    o.color = 'red';
    o.showColor = function () {
        alert(this.color);
    };
    o.showColor();
    
    // prototype
    function Car() {}
    Car.prototype.color = 'red';
    Car.prototype.doors = 4;
    Car.prototype.mpg = 23;
    Car.prototype.drivers = new Array('Mike', 'Sue');
    Car.prototype.showColor = function () {
        alert(this.color);
    };
    var oCar1 = new Car();
    var oCar2 = new Car();
    oCar1.drivers.push('Matt');
    alert(oCar1.drivers); //outputs “Mike,Sue,Matt”
    alert(oCar2.drivers); //outputs “Mike,Sue,Matt”
    
    // prototype && constructor
    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”
    
    // Dynamic prototype method
    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;
        }
    }
  • 相关阅读:
    iOS-导航条
    iOS-存储
    iOS-模型传递
    iOS-日期相关
    iOS-UIViewController
    iOS-loadView方法
    iOS-UIWindow
    Spring 测试
    Spring条件注解@Conditional
    Spring多线程
  • 原文地址:https://www.cnblogs.com/arist/p/3341164.html
Copyright © 2011-2022 走看看