What does the Javascript expression 'a = a || function() {…}' mean?

前端 未结 4 1325
执念已碎
执念已碎 2020-12-28 17:53

I\'m not sure what this construct means but I\'ve seen it a few times. The example below is from another Stack Overflow question. I\'m not sure how to interpret the initial

4条回答
  •  礼貌的吻别
    2020-12-28 18:22

    From what I can tell, that code attempts to define the function Object.keys if it isn't already defined (or if it's false). The function to the left of || will become the function Object.keys.

    The reason I said "from what I can tell" is that you haven't posted the entire code snippet. Notice that the code after || reads (function(){ instead of just function(){. It's possible that the author has set up the function to be self invoking.

    If, after the function definition, you see })(), then the return value of the function is stored in Object.keys. If not, then the function itself is stored there.

提交回复
热议问题