[javascript] JavaScript 함수를 재정의하는 방법

JavaScriptparseFloat 에서 내장 함수 를 재정의하려고합니다 .

어떻게할까요?



답변

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


답변

내장 함수를 다시 선언하여 재정의 할 수 있습니다.

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

이제 parseFloat(3)3을 알려줍니다.


답변

재정의하거나 바람직하게 다음과 같이 구현을 확장 할 수 있습니다.

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);

그리고 일반적으로 호출하는 것처럼 호출하십시오.

var result = parseFloat(1.345); // It should log the value 1.345 but get the value 0.345


답변

다음과 같이 할 수 있습니다.

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

여기에서 작동하는 예제를 확인하십시오 : http://jsfiddle.net/LtjzW/1/


답변