开发者

why I have two different result when I execute this javascript closure code

开发者 https://www.devze.com 2023-04-07 18:30 出处:网络
my code : var n; function f(){ var v = \"kevin\"; n = function(){ return v; } } execute i开发者_如何学JAVAn FireBug:

my code :

var n;
function f(){
   var v = "kevin";
   n = function(){
      return v;
   }
}

execute i开发者_如何学JAVAn FireBug: n(); the result is "kevin"

execute in Chrome & IE9:

document.writeln(n); ======>show "undefine" document.writeln(n()); ======>show nothing

I want to know what exactly the brows doing when execute the code. Thanks.

That code is a demo of the book "Object Oriented JavaScript", Chapter 3, Closure 2#


The variable n is not given a value (i.e., is not assigned to that function) until the function f() has been executed - which doesn't happen in the code you show.

So document.writeln(n); should show "undefined", while document.writeln(n()); should be an error since n is not a function.

I don't know why it works in FireBug - have you already executed f() when you try it?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号