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

前端 未结 4 1351
执念已碎
执念已碎 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:20

    This looks incomplete to me, but it seems as if it is a shim for Object.keys. Basically, if the property doesn't exist (in non standards compliant browsers, for example), we implement it ourselves.

    The or operator will evaluate the second operand only if the first one is falsy. As such

    alert(false || "Hello, world");
    

    Will alert "Hello, world". In this case, Object.keys would be undefined, which evaluates to false.

提交回复
热议问题