Javascript Function-Pointer Assignment

前端 未结 11 1060
广开言路
广开言路 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:30

    You are assigning the value of an anonymous function to a variable not a pointer.
    If you want to play with pointers, you can use objects that are passed by reference, not copy.

    Here are some examples:

    "obj2" is a reference of "obj1", you change "obj2", and "obj1" is changed. It will alert false.

    var obj1 = {prop:true},
        obj2 = obj1;
    obj2.prop = false;
    alert(obj1.prop);
    

    "prop" points to a property that is not an object, "prop" is not a pointer to this object but a copy. If you change "prop", "obj1" is not changed. It will alert true

    var obj1 = {prop:true},
        prop = obj1.prop;
    prop = false;
    alert(obj1.prop);
    

    "obj2" is a reference to the "subObj" property of "obj1". if "obj2" is changed, "obj1" is changed. It will alert false.

    var obj1 = {subObj:{prop:true}},
        obj2 = obj1.subObj;
    obj2.prop = false;
    alert(obj1.subObj.prop);
    

提交回复
热议问题