如何覆盖 JavaScript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5409428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:03:56  来源:igfitidea点击:

How to override a JavaScript function

javascript

提问by Riz

I'm trying to override a built in parseFloatfunction in JavaScript.

我正在尝试覆盖JavaScript 中的内置parseFloat函数。

How would I go about doing that?

我该怎么做呢?

回答by David Waters

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

回答by Rocket Hazmat

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

您可以通过重新声明任何内置函数来覆盖它。

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

Now parseFloat(3)will alert 3.

现在parseFloat(3)将警报 3。

回答by Anastasios Selmanis

You could override it or preferably extendit'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

回答by Kyle Wild

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/

在此处查看一个工作示例:http: //jsfiddle.net/LtjzW/1/