Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created July 22, 2014 00:14
Show Gist options
  • Save jikeytang/c95f42b08143a7972253 to your computer and use it in GitHub Desktop.
Save jikeytang/c95f42b08143a7972253 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140722-题目1
// 感谢深圳[时空]贡献 腾讯面试题一枚
f = function() {return true;};
g = function() {return false;};
(function() {
if (g() && [] == ![]) {
f = function f() {return false;};
function g() {return true;}
}
})();
console.log(f());
// true or false ? 为什么?
ps:
考察点:
作用域链(scope chain)、执行环境(execution context)、变量对象(variable object)命名函数表达式 等。
@sliwey-zz
Copy link

false
∵变量声明会提前
∴自执行函数中实际运行顺序如下

(function() {
  var g;
  if (g() && [] == ![]) {      // 此时g未被赋值 所以g()为undefined  即这个条件判断成立,会执行下述的语句
    f = function f() {return false;};  // 这个f为全局变量,覆盖了f的值
    g = function() {return true;};
  }
})();

由上可知,console.log(f()) 的值为false

@stephenykk
Copy link

in firefox: true ( because firefox don't hoist function declearation in blocks)
in chrome: false ( if中的函数声明是被提升了的)
if( g() && [] == ![] ) => if( (g()) && ( [] == ![]) ) //关系运算符优先级高于逻辑运算符 [] == ![] //true

@jikeytang
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment