How do I access the Object.prototype method in the following logic?

前端 未结 4 559
一个人的身影
一个人的身影 2020-12-23 14:24

I am using the following logic to get the i18n string of the given key.

export function i18n(key) {
  if (entries.hasOwnProperty(key)) {
    return entries[k         


        
相关标签:
4条回答
  • 2020-12-23 14:39

    You can access it via Object.prototype:

    Object.prototype.hasOwnProperty.call(obj, prop);
    

    That should be safer, because

    • Not all objects inherit from Object.prototype
    • Even for objects which inherit from Object.prototype, the hasOwnProperty method could be shadowed by something else.

    Of course, the code above assumes that

    • The global Object has not been shadowed or redefined
    • The native Object.prototype.hasOwnProperty has not been redefined
    • No call own property has been added to Object.prototype.hasOwnProperty
    • The native Function.prototype.call has not been redefined

    If any of these does not hold, attempting to code in a safer way, you could have broken your code!

    Another approach which does not need call would be

    !!Object.getOwnPropertyDescriptor(obj, prop);
    
    0 讨论(0)
  • 2020-12-23 14:49

    It seems like this would also work:

    key in entries

    since that will return a boolean on whether or not the key exists inside the object?

    0 讨论(0)
  • 2020-12-23 14:49

    I hope I won't get downvoted for this, probably will, but !

    var a = {b: "I'm here"}
    if (a["b"]) { console.log(a["b"]) }
    if (a["c"]) { console.log("Never going to happen") }
    

    Has, insofar, never broken my code

    0 讨论(0)
  • 2020-12-23 14:59

    For your specific case, the following examples shall work:

    if(Object.prototype.hasOwnProperty.call(entries, "key")) {
        //rest of the code
    }
    

    OR

    if(Object.prototype.isPrototypeOf.call(entries, key)) {
        //rest of the code
    }
    

    OR

    if({}.propertyIsEnumerable.call(entries, "key")) {
        //rest of the code
    }
    
    0 讨论(0)
提交回复
热议问题