Override JS function from another file

后端 未结 2 1108
梦毁少年i
梦毁少年i 2021-01-01 00:08

Im trying to override a JS function from Bigcartel. I have no access to the JS file.

The original is:

updateCart: function(cart) {
    $(\'aside .car         


        
2条回答
  •  生来不讨喜
    2021-01-01 00:21

    EDIT: You are in luck. From the posted code you can see that the updateCart method is exported on the window.Store global object. The solution is to add this code after the original script loaded:

    window.Store.updateCart = function(cart) {
      $('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
      return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
    };
    

    Explanation for a general situation:

    All scripts loaded in a web page run in the same global scope, so overwriting a variable is as simple as inserting your script afterwards:

    
    
    

    From the looks of it, your function is defined as property of an object:

    var x = {
       updateCart : function(cart) {
         // stuff
       }
    }
    

    So to overwrite it you need to do:

    x.updateCart = function(cart) {
      // your code
    }
    

    Finally, there is one situation where you simply can't overwrite it, if function is private in the original code:

    function() {
       var x = {
          updateCart: function(){}
       }
    }()
    
    // No way to access x.updateCart here
    

提交回复
热议问题