Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

Make javascript ignore a piece of code

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...