Prototype application in JS (inheritance and extension)

Prototypes in JS

Prototype is a very important mechanism in JavaScript. Through [[prototype]], we can easily implement the inheritance and extension of constructors and their instances.

The concept of prototype is shown in the figure below. For details, please refer to MDN This paper mainly talks about the application of prototype in practice.

Referring to the prototype mechanism in jQuery and zepto, the application of the prototype can be roughly divided into the following parts:

  • Define constructor
  • Define build instance interface
  • Define initialization function
  • Provide extension interface (plug-in mechanism)
  • Provide external interface
  • Binding prototype

Create a library file of your own (sojoin. JS)

(function (window) {
  // Define your own objects
  var Sojourn = {}

  // Define constructor
  function S(dom, selector) {
    var i, len = dom ? dom.length : 0;
    for (i = 0; i < len; i++) {
      this[i] = dom[i];
    }
    this.length = len;
    this.selector = selector || '';
  }

  // Define build instance interface
  Sojourn.S = function (dom, selector) {
    return new S(dom, selector);
  }

  // Define initialization function
  Sojourn.init = function (selector) {
    var slice = Array.prototype.slice;
    var dom = slice.call(document.querySelectorAll(selector));
    return Sojourn.S(dom, selector);
  }

  // Provide external interface
  var $ = Sojourn.init;

  // Provide extension interface
  $.fn = {
    constructor: Sojourn.S,
    // Adding method

    // Define a method to modify the html content of an element
    html: function (content) {
      console.log(this);
      if (content) {
        this[0].innerHTML = content;
      } else {
        alert('no change');
      }
      // Return dom object to implement chain call
      return this;
    }
  }

  // Binding prototype
  Sojourn.S.prototype = S.prototype = $.fn;

  // Bind to global object
  window.$ = $;
})(window)

Using sojoin.js in HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>prototype-test</title>
</head>

<body>
  <div id="div1">prototype test</div>

  <script src="./sojourn.js"></script>
  <script>
    // One second later, use the method of construction to change dom elements
    setTimeout(function () {
      var div1 = $('#div1');
      // call chaining
      div1.html().html('use Sojourn.js');

      // Extension plug-in
      $.fn.getNodeName = function () {
        alert(this[0].nodeName);
      }

      div1.getNodeName();
    }, 1000);
  </script>
</body>

</html>

Click to jump to my GitHub

reference material:
MDN
JS you don't know (Volume I)

Tags: Javascript JQuery IE github

Posted on Wed, 08 Jan 2020 13:18:24 -0500 by christo16