gpt4 book ai didi

javascript - "void 0 "和 "undefined"之间的区别

转载 作者:IT王子 更新时间:2023-10-29 02:55:37 26 4
gpt4 key购买 nike

我正在使用 "Closure Compiler" ,在编译我的脚本时,我花费了以下内容:

编译前:

// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print,print_input_delimiter
// ==/ClosureCompiler==

var myObj1 = (function() {

var undefined; //<----- declare undefined

this.test = function(value, arg1) {

var exp = 0;
arg1 = arg1 == undefined ? true : arg1; //<----- use declare undefined
exp = (arg1) ? value * 5 : value * 10;

return exp;
};

return this;
}).call({});

var myObj2 = (function() {

this.test = function(value, arg1) {

var exp = 0;
arg1 = arg1 == undefined ? true : arg1; //<----- without declare undefined
exp = (arg1) ? value * 5 : value * 10;

return exp;
};

return this;
}).call({});

编译:

// Input 0
var myObj1 = function() {
this.test = function(b, a) {
a = a == void 0 ? true : a; //<-----
var c = 0;
return c = a ? b * 5 : b * 10
};
return this
}.call({}), myObj2 = function() {
this.test = function(b, a) {
a = a == undefined ? true : a; //<-----
var c = 0;
return c = a ? b * 5 : b * 10
};
return this
}.call({});

有了这个我相信“void 0”和“undefined”的使用问题,在使用上有什么区别还是两种情况都很好?

编辑

如果我定义用“void 0”编译的“var undefined”,如果我没有定义用“undedined.”编译的“undefined”,那么“undefined”和“void 0”之间的字符数不是问题

Test

编辑 II:性能,基于 this link

Code and Test

IE 8:
typeof: 228ms
未定义:62ms
无效 0:57 毫秒

火狐 3.6:
类型:10ms
未定义:3ms
无效 0: 3ms

歌剧 11:
类型:67ms
未定义:19ms
void 0: 20ms

Chrome 8:
类型:3ms
未定义:5ms
无效 0: 3ms

最佳答案

From MDN :

The void operator evaluates the given expression and then returns undefined.

This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

Closure Compiler 在 void 0 中交换,因为它包含的字符少于 undefined因此生成等效的、更小的代码


回复:OP 评论

yes, I read the documentation, but in the example I gave, "google closure" in a case using "void 0" and another "undefined"

我相信这实际上是一个 bug in Google Closure Compiler !

关于javascript - "void 0 "和 "undefined"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4806286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com