Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

Example: Live Copy | Source

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...