Override JS function from another file

二次信任 提交于 2019-11-30 14:16:46

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:

<script>
var x = 5; // original script
</script>
<script>
x = 2; // your inserted script
</script>

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

Assuming you're able to find and access corresponding js object:

[theTargetObject].prototype.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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!