Can you alter a Javascript function after declaring it?

前端 未结 12 775
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 22:10

Let\'s say I have var a = function() { return 1; }. Is it possible to alter a so that a() returns 2? Perhaps by editing a

相关标签:
12条回答
  • 2020-11-28 22:45

    You can do all kinds of fun stuff with javascript, including redefining functions:

    var a = function(){ return 1; }
    
    alert(a()); //1
    
    // keep a reference
    var old = a;
    
    // redefine
    a = function(){
      // call the original function with any arguments specified, storing the result
      var originalResult = old.apply(old, arguments);
      // add one
      return originalResult + 1;
    };
    alert(a()); //2
    

    Voila.

    Edit: Updated to show this in a crazier scenario:

    var test = new String("123");
    console.log(test.toString()); // logs 123
    console.log(test.substring(0)); // logs 123
    String.prototype.substring = function(){ return "hahanope"; }
    console.log(test.substring(0)); // logs hahanope
    

    You can see here that even though "test" is defined first, and we redefine substring() afterwards, the change still applies.

    Side note: you really should reconsider your architecture if you're doing this...you're going to confuse the crap out of some poor developer 5 years down the road when s/he's looking at a function definition that's supposed to return 1, but seems to always return 2....

    0 讨论(0)
  • 2020-11-28 22:47

    So you want to modify the code of a function directly, in place, and not just reassign a different function to an existing variable.

    I hate to say it, but as far as I have been able to figure it out - and I have tried -, it can't be done. True, a function is an object, and as such it has methods and properties which can be tweaked and overwritten on the object itself. Unfortunately, the function body is not one of them. It is not assigned to a public property.

    The documentation on MDN lists the properties and methods of the function object. None of them gives us the opportunity to manipulate the function body from the outside.

    That's because according to the spec, the function body is stored in the internal [[Code]] property of the function object, which can't be accessed directly.

    0 讨论(0)
  • 2020-11-28 22:48

    If you're debugging javascript and want to see how changes to the code affects the page, you can use this Firefox extension to view/alter javascripts:

    Execute JS firefox extension: https://addons.mozilla.org/en-US/firefox/addon/1729

    0 讨论(0)
  • 2020-11-28 22:54

    How about this, without having to redefine the function:

    var a = function() { return arguments.callee.value || 1; };
    alert(a()); // => 1
    a.value = 2;
    alert(a()); // => 2
    
    0 讨论(0)
  • 2020-11-28 22:54

    Absolutely. Just assign to it a new function.

    0 讨论(0)
  • 2020-11-28 22:55

    This is a Clear Example based on a control timepicker eworld.ui www.eworldui.net

    Having a TimePicker eworld.ui where JavaScript is unreachable from outside, you can't find any js related to those controls. So how can you add a onchange event to the timepicker ?

    There is a js function called when you Select a time between all the options that the control offer you. This function is: TimePicker_Up_SelectTime

    First you have to copy the code inside this function.

    Evaluate...quikwatch...TimePicker_Up_SelectTime.toString()

    function TimePicker_Up_SelectTime(tbName, lblName, divName, selTime, enableHide, postbackFunc, customFunc) {
        document.getElementById(tbName).value = selTime;
        if(lblName != '')
            document.getElementById(lblName).innerHTML = selTime;
        document.getElementById(divName).style.visibility = 'hidden';
        if(enableHide)
            TimePicker_Up_ShowHideDDL('visible');
        if(customFunc != "")
            eval(customFunc + "('" + selTime + "', '" + tbName + "');");
        eval(postbackFunc + "();");
    }
    

    Now

    Using the code that you have saved before reassign the same source code but add whatever you want..

    TimePicker_Up_SelectTime = function (tbName, lblName, divName, selTime, enableHide, postbackFunc, customFunc) {
        document.getElementById(tbName).value = selTime;
        if (lblName != '')
            document.getElementById(lblName).innerHTML = selTime;
        document.getElementById(divName).style.visibility = 'hidden';
        if (enableHide)
            TimePicker_Up_ShowHideDDL('visible');
        if (customFunc != "")
            eval(customFunc + "('" + selTime + "', '" + tbName + "');");
        eval(postbackFunc + "();");
    
        >>>>>>>  My function  >>>>>   RaiseChange(tbName);
    }
    

    I've added My Function to the function so now I can simulate an onchange event when I select a time.

    RaiseChange(...) could be whatever you want.

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