How can you purposely make javascript ignore a piece of code. That is: if you have something like this:
function hello() { console.log('hello'); }
Is there a way to make javascript ignore this and not create a function name hello
? Can this be done in pure javascript?
Assuming you can't remove or comment out that code, no, you can't prevent the function from being created.
You can , though, disconnect the function from the hello
symbol:
hello = undefined;
Now you can't call the function via that symbol anymore, and if it was the only reference to the function, the function is eligible for GC.
function hello() { console.log("Hello"); }
console.log("Before setting <code>hello = undefined;</code>");
try {
hello();
}
catch (e1) {
console.log("Exception on 'before' call: " + (e1.message || String(eq)));
}
hello = undefined;
console.log("After setting <code>hello = undefined;</code>");
try {
hello();
}
catch (e2) {
console.log("Exception on 'after' call: " + (e2.message || String(eq)));
}
Output:
Before setting hello = undefined; Hello After setting hello = undefined; Exception on 'after' call: undefined is not a function
You can override that function to do nothing, for example:
hello = function(){}
As i saw in your comment. You only want to ignore this code but still want to use it later. So I think you might want to try this:
1- Save the function pointer
var oldHello = hello;
2- Override it
hello = function() {}
3- Restore for later use
hello = oldHello;
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.