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

后端 未结 5 536
清酒与你
清酒与你 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 04:12

    Either or both of those techniques may apply depending on the situation.

    The value of this within a function depends on how the function was called. If you call a function as property of an object like this:

    obj.key2();
    //or
    obj["key2"]();
    

    Then this will be that object. Whether the object was created via an object literal or some other means is not relevant.

    But you can use .call() or .apply() to call a function and explicitly set this to some other object.

    Consider also:

    var obj = {
        key1: "it",
        key2: function(){return this.key1 + " works!"}
    };
    alert(obj.key2()); // alerts "it works!"
    
    var func = obj.key2;
    alert(func())​;     // alerts "undefined works!"
    

    I'm setting up func to reference the same function as obj.key2, but calling it as func() does not set this to obj.

    For more information have a look at what MDN has to say about this.

提交回复
热议问题