对Javascript中具有属性的函数的引用的困惑 [英] Confusion over references to functions with properties in Javascript

查看:57
本文介绍了对Javascript中具有属性的函数的引用的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下javascript代码中:

  function foo(){
foo.val = foo.val | | '没有val';
返回'foo has'+ foo.val;
};
功能栏(){
bar.val = bar.val || '没有val';
返回'bar has'+ bar.val;
};
var a = foo;
foo.val ='1';
bar.val ='2';
a.val ='3';
foo = bar;
'foo说'+ foo()+',bar说'+ bar()+',a表示'+ a()+'';

我期望的是:


foo说酒吧有2,酒吧说酒吧有2,a说foo有3


但是,当从Firefox 10.0.2中的Firebug控制台运行时,我得到:


foo说bar有2, bar说bar有2,a表示foo有2


任何人都可以向我解释发生的事件顺序在幕后制作这样的话?为什么 a 保持绑定到原来的 foo 函数(正如我所料)但是持有 bar val的值

解决方案

在这行代码之后:

  var a = foo; 

a 指向与 foo 指向。在

  foo = bar; 

你重新分配 foo 指向任何 bar 指的是。这不会更新 a 的引用 - 它仍然指向 foo 最初也指向的函数。 / p>

现在,当您运行 a()时,将执行原始函数。它抓取 foo (现在指向 bar 的引用)并获取其 val property。 bar val 的对象是2,所以这就是返回的内容。



用文字解释有点困难..或许图表会更容易理解吗?


In the following javascript code:

function foo() {
  foo.val =  foo.val || 'no val';
  return 'foo has ' + foo.val;
};
function bar() {
  bar.val =  bar.val || 'no val';
  return 'bar has ' + bar.val;
};
var a = foo;
foo.val = '1';
bar.val = '2';
a.val = '3';
foo = bar;
'foo says "' + foo() + '", bar says "' + bar() + '", a says "' + a() +'"';

what I would expect would be:

foo says "bar has 2", bar says "bar has 2", a says "foo has 3"

However, when run from the Firebug console in Firefox 10.0.2 I get:

foo says "bar has 2", bar says "bar has 2", a says "foo has 2"

Can anyone explain to me the sequence of events that goes on behind the scenes to make this so? Why does a stay bound to the original foo function (as I would expect) but hold bar's value for val?

解决方案

After this line of code:

var a = foo;

a points to the same function that foo points to. In

foo = bar;

you reassign foo to point to whatever bar refers to. This doesn't update a's reference — it still points to the function that foo also originally pointed to.

Now, when you run a(), the original function is executed. It grabs foo (which now points to bar's reference) and gets its val property. The val of bar's object is 2, so this is what is returned.

It's a bit difficult to explain in words.. would a diagram be easier to understand, perhaps?

这篇关于对Javascript中具有属性的函数的引用的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆