How to implement apply pattern in Javascript

前端 未结 3 1468
刺人心
刺人心 2021-02-06 11:04

What is apply invocation pattern in Javascript in reference to function invocation patterns and how can I use it? What are the benefits of using this invocation pattern.

3条回答
  •  無奈伤痛
    2021-02-06 11:46

    You can also use call/apply for inheritance.

    function Client (id) {
      this.id = id;
      this.name = "Client" + id;
    }
    
    Client.prototype = {
        constructor: Client
    
      , toString: function () {
          return this.name;
        }
    };
    
    function WebClient (id) {
      Client.call (this, id);
    }
    
    WebClient.prototype = new Client ();
    
    WebClient.prototype.constructor = WebClient;
    
    WebClient.prototype.ping = function () {
      // do stuff
    };
    

    Notice Client.call (this, id); This executes Client using the this instance that a new WebClient would create. Thus when

      this.id = id;
      this.name = "Client" + id;
    

    are executed inside Client the WebClient instance is getting assigned those properties.

提交回复
热议问题