zoukankan      html  css  js  c++  java
  • JavaScript Patterns 5.6 Static Members

    Public Static Members

    // constructor
    
    var Gadget = function (price) {
    
        this.price = price;
    
    };
    
    // a static method
    
    Gadget.isShiny = function () {
    
        // this always works
    
        var msg = "you bet";
    
        // Checking if the static method is called by instance.
    
        if (this instanceof Gadget) {
    
            // this only works if called non-statically
    
            msg += ", it costs $" + this.price + '!';
    
        }
    
        return msg;
    
    };
    
    
    // a normal method added to the prototype
    
    Gadget.prototype.setPrice = function (price) {
    
        this.price = price;
    
    };
    
    
    // a normal method added to the prototype
    
    Gadget.prototype.isShiny = function () {
    
        return Gadget.isShiny.call(this);
    
    };
    
    
    // Attempting to call an instance method statically won’t work
    
    typeof Gadget.setPrice; // "undefined"

     

    Testing a static method call:

    Gadget.isShiny(); // "you bet"

     

    Testing an instance, nonstatic call:

    var a = new Gadget('499.99');
    
    a.isShiny(); // "you bet, it costs $499.99!"

    Private Static Members

    • Shared by all the objects created with the same constructor function

    • Not accessible outside the constructor

    // constructor
    
    var Gadget = (function () {
    
        // static variable/property
    
        var counter = 0,
    
            NewGadget;
    
        // this will become the new constructor implementation
    
        NewGadget = function () {
    
            counter += 1;
    
        };
    
        // a privileged method
    
        NewGadget.prototype.getLastId = function () {
    
            return counter;
    
        };
    
        // overwrite the constructor
    
        return NewGadget;
    
    }()); // execute immediately
    
    
    var iphone = new Gadget();
    
    iphone.getLastId(); // 1
    
    var ipod = new Gadget();
    
    ipod.getLastId(); // 2
    
    var ipad = new Gadget();
    
    ipad.getLastId(); // 3

    References: 

    JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

  • 相关阅读:
    netcore 发布到IIS上常见错误
    mysql解压文件安装
    VS2017 怎么启用nuget程序包还原?
    vue-qr生成下载二维码
    控制器,action, 过滤器, 权限
    WebSocket浅析(一):实现群聊功能
    BOM元素之window对象
    arguments及arguments.callee
    Spring入门6事务管理2 基于Annotation方式的声明式事务管理机制
    Spring入门5.事务管理机制
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Static-Members.html
Copyright © 2011-2022 走看看