Is there a way to catch an attempt to access a non existant property or method?

后端 未结 4 1526
星月不相逢
星月不相逢 2020-12-06 00:56

For instance this code:

function stuff() {
  this.onlyMethod = function () {
    return something;
  }
}

// some error is thrown
stuff().nonExistant();
         


        
4条回答
  •  星月不相逢
    2020-12-06 01:17

    It seems that you know your way around JS. Unfortunately, I don't know of such feature in the language, and am pretty sure that it does not exist. Your best option, in my opinion is either using a uniform interface and extend it, or extend the prototypes from which your objects inherit (then you can use instanceof before going forward with the method call) or use the somewhat cumbersome '&&' operator in order to avoid the access of nonexistent properties/methods:

    obj.methodName && obj.methodName(art1,arg2,...);
    

    You can also extend the Object prototype with Anurag's suggestion ('call').

提交回复
热议问题