Javascript Function-Pointer Assignment

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

    Those are not function pointers (and there are no pointers in JS natively). Functions in JS can be anonymous and are first class objects. Hence

    function () { alert("A"); }
    

    creates an anonymous function that alerts "A" on execution;

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

    assign that function to bar;

    var foo = bar;
    

    assign foo to bar, which is the function "A".

    bar = function () { alert("B"); };
    

    rebind bar to an anonymous function "B". This won't affect foo or the other function "A".

    foo();
    

    Call the function stored in foo, which is the function "A".


    Actually in languages where there are function points e.g. C it won't affect foo either. I don't know where you get the idea of getting "B" on reassignment.

    void A(void) { printf("A\n"); }
    void B(void) { printf("B\n"); }
    typedef void(*fptr_t)(void);
    fptr_t foo = A;
    fptr_t bar = foo;
    bar = B;
    foo(); // should print "A"
    

提交回复
热议问题