谁能解释为什么这些slides中的Java代码失败?

var ninja = {
  yell: function(n){
    return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
  }
};
assert( ninja.yell(4) == "hiyaaaa", "A single object isn't too bad, either." );

var samurai = { yell: ninja.yell };
var ninja = null;

try {
  samurai.yell(4);
} catch(e){
  assert( false, "Uh, this isn't good! Where'd ninja.yell go?" );
}

最佳答案

该参考仍然保持:

var samurai = { yell: ninja.yell };


因此,对.yell()的调用很好,但是这不是:

return n > 0 ? ninja.yell(n-1) + "a" : "hiy";


该调用实际上引用的是ninja,现在是null,而null.yell()不是函数:)

Here's a modified version that shows the problem

关于javascript - 对象设置为null时函数调用失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3580757/

10-11 14:09