为什么自定义函数引用不断指向旧函数 [英] why self defining function reference keeps pointing to the old function

查看:33
本文介绍了为什么自定义函数引用不断指向旧函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在"javascript设计模式"中找到了此示例,并将其与以下代码的行为相混淆

I find this example in "javascript design patterns" and confused with the behavior of following code

此代码创建一个自定义函数:

this code creates a self defining function:

var scareMe = function () {
   alert("Boo!");
   scareMe = function () {
     alert("Double boo!");
  };
};

现在我们将其引用到另一个变量

now we are referencing it to another variable

var prank = scareMe; 

令人困惑的部分是,当我打电话给恶作剧时,它应该更新scareMe,而当我回叫它时,它应该警告"Double boo",不是吗?

confusing part is when I called prank it should update scareMe and when i call it back it should alert "Double boo" isn't it?

但结果是

prank(); // "Boo!"
prank(); // "Boo!"

,如果我检查一下scareMe函数,则确实已对其进行了重新定义.

and if I check scareMe function indeed it has been redefined.

scareMe(); // Double boo!

恶作剧仅仅是对scareMe的引用,比为什么有区别?

prank is just a reference to scareMe than why there is a difference?

推荐答案

恶作剧指向原始功能,而不是 scareMe .

prank points at the original function, not to scareMe.

看这个例子:

var scareMe = 1;
var prank = scareMe;

scareMe = 2;

您不希望更改 scareMe 会更改 prank ,对吗?函数完全一样.

You don't expect that changing scareMe would change prank, right? It's exactly the same with functions.

var scareMe = function() { alert( 'Boo' ); };
var prank = scareMe;

scareMe = function() { alert( 'Double boo!' ); };

在这方面,整数和函数之间没有区别,即使 scareMe 发生变化, prank 也保持不变.从另一个函数内部更改了 scareMe 并不会改变这一事实.

There is no difference between integers and functions in this regard—prank stays the same, even when scareMe changes. That scareMe is changed from inside another function does not change this fact.

混淆可能来自通常如何使用对象.突变原始功能并不像更改对象属性那样普遍.

The confusion might come from how objects are usually used. It's not as common to mutate the original function as you might change an object's properties.

var scareMe = { message: 'Boo' };
var prank = scareMe;

scareMe.message = 'Double boo!';

alert( prank.message );  // alerts 'Double boo!'

这不是您在原始示例中对函数所做的事情.更改变量以指向完全不同的函数不会更改另一个变量中的函数引用.

This is not what you're doing with functions in the original example. Changing a variable to point to a completely different function does not change the function reference in the other variable.

这篇关于为什么自定义函数引用不断指向旧函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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