Javascript Function-Pointer Assignment

前端 未结 11 1059
广开言路
广开言路 2020-12-04 12:05

Consider this javascript code:

var bar = function () { alert(\"A\"); }
var foo = bar;
bar = function () { alert(\"B\"); };
foo();

When runn

11条回答
  •  醉梦人生
    2020-12-04 12:56

    I'm a bit late here but I thought I'd give an answer anyways and flesh something out.

    It's best not to think in terms of pointers and memory references when discussing the internals of JavaScript (or ECMAScript) when dealing with the specifications. Variables are environment records internally and are stored and referenced by name, not memory address. What your assignment statement is doing, internally and by design, is looking up the environment record name (either "foo" or "bar") and assigning the value to that record.

    So,

    var bar = function () { alert("A"); }
    

    is assigning the environment record "bar" the value (anonymous function).

    var foo = bar;
    

    internally calls GetValue("bar") which retrieves the value associated with the record "bar" and then associates that value with the record "foo". Hence, afterwards the original value of bar can still be used as it's now associated with foo.

    Because JavaScript references by string and not memory address is precisely why you can do things like this:

    someObject["someProperty"]
    

    which is looking up the value based on the property name.

提交回复
热议问题