[removed] Object Literal reference in own key's function instead of 'this'

后端 未结 5 547
清酒与你
清酒与你 2020-11-22 03:18

Is it problematic to reference an object literal within a function which is part of that very literal? It seems to work just fine, but I want to make sure there aren\'t othe

5条回答
  •  自闭症患者
    2020-11-22 03:55

    There will be a difference in variable scope binding. If you modify obj later, you will modify the return value of key2:

    var newobj = obj;
    obj = { key1: "new" };
    alert(newobj.key2());
    

    Now it alerts "new works!", because even though you are calling key2() on the original object (which is now newobj), the reference to obj.key1 now binds to the value of the new obj instance. Using this prevents this from happening.

    Demo: http://jsfiddle.net/m6CU3/

提交回复
热议问题