Javascript Function-Pointer Assignment

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

    In other examples, nothing was passed by value; everything was passed by reference.

    bar and foo are BOTH pointers

    All vars/handles to NON primitive objects in javascript are pointers; pointers ARE native to javascript, they are the default.

    var bar = function () { alert("A"); } //bar is a pointer to function1
    var foo = bar;  //pointer copied; foo is now also a pointer to function1
    bar = function () { alert("B"); };  //bar points to function2
    foo();  //foo is still a pointer to function1
    

    You will run into hidden errors and bugs if you think they are copies. Especially so if you work with complex objects. For example

    function person(name){this.name = name}
    var john = new person("john")
    var backup = john
    backup.name //john
    john.name = "jack"
    backup.name //jack, NOT john
    

    To really COPY a non-primitive in javascript takes more work than just a = b. For example:

    function person(name){  this.name = name}
    var john = new person("john")
    var backup = new Object()
    backup = JSON.parse(JSON.stringify(john))
    backup.__proto__ = john.__proto__   //useful in some cases
    john.name = "jack"
    backup.name //john
    

提交回复
热议问题