JavaScript静态和常量

作者: 张歆琳 | 来源:发表于2016-07-22 13:39 被阅读399次

    JavaScript模块里介绍了用模块实现封装的方式。传统OO语言里还有两个重要特性就是静态和常量,但JavaScript里没有static和const关键字。本篇就介绍一下JavaScript里如何实现它们。

    静态

    分公有静态和私有静态。公有静态成员是不需要实例化对象就能直接运行的:

    var Person = function () {};    //构造函数
    
    Person.sayHi = function () {  //公有静态方法
        return "hi";
    }
    Person.prototype.setAge = function (a) { //实例方法
        this.age = a;
    }
    Person.prototype.getAge = function (a) { //实例方法
        return this.age;
    }
    
    Person.sayHi();         //hi
    
    var p1 = new Person();
    p1.setAge(33);
    console.log(p1.getAge());   //33
    
    var p2 = new Person();
    p2.setAge(25);
    console.log(p2.getAge());   //25
    
    console.log(typeof Person.sayHi);    //function
    console.log(typeof Person.setAge);   //undefined
    console.log(typeof Person.getAge);   //undefined
    console.log(typeof p1.sayHi);        //undefined
    console.log(typeof p1.setAge);       //function
    console.log(typeof p1.getAge);       //function
    

    上例中静态方法可以直接运行,而实例化的对象里并不存在静态方法。因此实例化对象的改变不会影响到静态成员。

    如果要静态方法与实例方法一起工作,很简单,可采用外观模式的思想来组织代码:

    Person.prototype.sayHi = Person.sayHi;
    p1.sayHi();   //hi
    

    但上面这样的话,在静态方法内使用this要小心。Person.sayHi();里的this指向Person的构造函数。p1.sayHi();里的this指向p1,基于这个特点,可以让静态和非静态都调用同一个方法,让其行为不同:

    var Person = function (n) { //构造函数
        this.name = n;
    };
    Person.sayHi = function () {  //静态方法
        var msg = "hi";
        if (this instanceof Person) {   //实例调用静态方法
            msg += (" " + this.name);
        }
        return msg;
    }
    Person.prototype.sayHi = function () {    //实例方法
        return Person.sayHi.call(this);
    }
    
    Person.sayHi();   //hi,因为this是function
    var p1 = new Person("Jack");
    p1.sayHi();      //hi Jack,因为this是object
    

    私有静态成员,对该类的用户而言是不可见的,但仍旧可以在类的多个实例间共享。

    var Count = (function () {
        var counter = 0;    //私有静态属性
    
        return function () {
            console.log(counter+=1);
        }
    }());
    
    var c1 = new Count();  //1
    var c2 = new Count();  //2
    var c3 = new Count();  //3
    

    这种静态属性其实很有用,可以通过特权方法将其公开,例如增加一个getLastCount():

    var Count = (function () {
        var counter = 0,    //私有静态属性
            NewCount;
    
        NewCount = function () {    //新构造函数
            counter += 1;
        }
        NewCount.prototype.getLastCount = function () {
            return counter;
        }
    
        return NewCount;    //覆盖构造函数
    }());
    
    var c1 = new Count();
    console.log(c1.getLastCount());    //1
    var c2 = new Count();
    console.log(c2.getLastCount());    //2
    var c3 = new Count();
    console.log(c3.getLastCount());    //3
    

    在单例模式中常见该例子。

    公有或私有的静态成员会带来很多便利,它们独立于实例对象,不受实例对象的影响,可以将需要共享,非实例相关的属性或方法定义成静态。

    常量

    自定义的常量通常用大写字母,但这只是一种约定,无意中改了也不易发现。如果没必要做的这么严谨,或团队对这潜规则都心知肚明,那用大写字母就OK了。否则的话,我们希望有真正的常量,例如:

    Math.PI = 2;
    console.log(Math.PI);   //3.1415926,不变
    

    我们可以自定义一个常量模块,提供3个方法:isDefined验证该常量是否已经被定义过。get / set方法用于取设常量。一旦常量被set过后,就无法再次被set。

    var constant = (function () {
        var constants = {},
            ownProp = Object.prototype.hasOwnProperty,
            allowed = {
                string: 1,
                number: 1,
                boolean: 1
            },
            perfix = (Math.random() + "_").slice(2);
    
        return {
            isDefined: function (name) {        //是否已经定义过
                return ownProp.call(constants, perfix + name);
            },
            set: function (name, value) {
                if (this.isDefined(name)) {
                    return false;
                }
                if (!ownProp.call(allowed, typeof value)) {
                    return false;
                }
                constants[perfix + name] = value;
                return true;
            },
            get: function (name) {
                if (this.isDefined(name)) {
                    return constants[perfix + name];
                }
                return null;
            }
        };
    }());
    
    console.log(constant.isDefined("maxwidth")); //false
    console.log(constant.set("maxwidth", 200));  //true
    console.log(constant.get("maxwidth"));       //200
    console.log(constant.isDefined("maxwidth")); //true
    console.log(constant.set("maxwidth", 400));  //false
    console.log(constant.get("maxwidth"));       //200不变
    

    其他细节说明一下,被定义的常量,统一保持到私有属性constants里。只支持allowed里的3种类型的值(当然你可以扩展或删减)。为保证常量名和内置属性名不冲突(例如用户定义一个名叫toString的常量),在模块内部给常量名加上随机数前缀。

    相关文章

      网友评论

        本文标题:JavaScript静态和常量

        本文链接:https://www.haomeiwen.com/subject/zljijttx.html