Search code examples
javascriptprototypejspdfprototype-chain

can't find the method I added to the external javascript library


I'm a new for Javascript. I wanted to add a method to the external library named jsPDF. so I tried to add a function named 'addHangle' to jsPDF.prototype But the object of jsPDF didn't find my method.

I've tried debugging and I found out jsPDF.prototype is pointer for Object.prototype

Why does it happend? I thought doc.construct is pointer for jsPDF and doc.__proto__ is pointer for jsPDF.prototype

Is there anyone know the reason? please tell me. my code is below.

jsPDF.prototype.addHangle = function(x, y, text) { 
  // some logic for supporting Korean
};

var doc = new jsPDF();
doc.addHangle();

Solution

  • Because jsPDF constructor returns API object. Following example might help you to understand why doc's prototype is not a jsPDF

    var P = function() {
        var API = {};
    
        // This is constructor of P
        function P() {
          // Do something...
          API.a = function(val){return val};
          return API;
        }
    
        return P;
    };
    
    var p = new P();
    var result = p instanceof P; // false
    

    You can see what really happens when new jsPDF() called at jsPDF GitHub

    If you want to insert your own method, you have to make it as jsPDF plugin. You can refer other plugins of jsPDF at https://github.com/MrRio/jsPDF/tree/master/plugins