1

How do you completely replace a function in JavaScript?

I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?

<html>
<head>
 <script id="myScript" type="text/javascript">
 function someFunction() {
 alert("Same old.");
 }
 </script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
 function replace() {
 var oldFunctionString = someFunction.toString();
 var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
 var newCode = "alert(New code!);"; 
 var newFunctionString = "function someFunction(){"+newCode+"}";
 var scriptTag = document.getElementById('myScript');
 scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
 }
 replace();
</script>
</body>
</html>

JSfiddle here

asked Nov 3, 2012 at 16:35

2 Answers 2

6

Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).

If you want to replace that function, just use

somefunction = function() {
 alert(New code!); // syntax error, btw
};

Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:

somefunction = eval("("
 + somefunction.toString().replace(/(alert\().*?(\);)/, "1ドルNew code!2ドル")
 + ")");
answered Nov 3, 2012 at 16:38
Sign up to request clarification or add additional context in comments.

Comments

2

It seems you are trying to work with strings, not the function itself. Just do this instead:

someFunction = function () { /* your function code here */ }
answered Nov 3, 2012 at 16:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.