How to override a JavaScript function

后端 未结 4 682
栀梦
栀梦 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题