How to override a JavaScript function

后端 未结 4 657
栀梦
栀梦 2020-11-28 04:34

I\'m trying to override a built in parseFloat function in JavaScript.

How would I go about doing that?

相关标签:
4条回答
  • 2020-11-28 05:21

    You could override it or preferably extend it's implementation like this

    parseFloat = (function(_super) {
        return function() {
            // Extend it to log the value for example that is passed
            console.log(arguments[0]);
            // Or override it by always subtracting 1 for example
            arguments[0] = arguments[0] - 1;
            return _super.apply(this, arguments);
        };         
    
    })(parseFloat);
    

    And call it as you would normally call it:

    var result = parseFloat(1.345); // It should log the value 1.345 but get the value 0.345
    
    0 讨论(0)
  • 2020-11-28 05:24

    You can override any built-in function by just re-declaring it.

    parseFloat = function(a){
      alert(a)
    };
    

    Now parseFloat(3) will alert 3.

    0 讨论(0)
  • 2020-11-28 05:39
    var origParseFloat = parseFloat;
    parseFloat = function(str) {
         alert("And I'm in your floats!");
         return origParseFloat(str);
    }
    
    0 讨论(0)
  • 2020-11-28 05:39

    You can do it like this:

    alert(parseFloat("1.1531531414")); // alerts the float
    parseFloat = function(input) { return 1; };
    alert(parseFloat("1.1531531414")); // alerts '1'
    

    Check out a working example here: http://jsfiddle.net/LtjzW/1/

    0 讨论(0)
提交回复
热议问题