hasOwnProperty未捕获的TypeError

时间:2018-11-14 11:14:09

标签: javascript

我尝试了解在已定义对象的上下文之外调用hasOwnProperty()的错误消息。即代替myObj.hasOwnProperty('propName'),只需:

hasOwnProperty('propName')

错误消息是:

  

VM269:1 Uncaught TypeError: Cannot convert undefined or null to object      
at hasOwnProperty (<anonymous>)      
at <anonymous>:1:1

我期望的错误:

  

VM280:1 Uncaught ReferenceError: hasOwnProperty is not defined   
at <anonymous>:1:1

转换失败到底是什么?

console.log(window.hasOwnProperty('blur'));
hasOwnProperty('propName');


编辑:

我认为人们会误解我的问题。我了解您通常像myObj.hasOwnProperty('propName')这样调用它。我想更好地了解它引发的错误。 什么是转换失败了吗?如@Felix所述,它应该隐式地退回到window.hasOwnProperty('propName')


编辑2:

有趣的是,我将developer.mozilla.org的Polyfill重命名为new_hasOwnProperty,它可以正常工作:

try{
    hasOwnProperty('blur');
}
catch(error) { console.log(error.message); }

// Polyfill
(function(w) {
  var isFunction = w.isFunction || (w.isFunction = function(x) {
      return typeof(x) === 'function'
    }),
    has = w.has || (w.has = function(o, p) {
      var e = p in o;
      return {
        value: e && (e = o[p]) && true,
        refer: e,
        valueOf: function() {
          return this.value
        }
      }
    }),
    Polyfill = w.PolyfillMethod || (w.PolyfillMethod = function(o, p, x) {
      var e = has(o, p);
      if (e && (e = isFunction(e.refer)) === false) {
        o[p] = x
      };
      return e
    }),
    theProto = w.Object.prototype;

  Polyfill(theProto, 'new_hasOwnProperty', function(x) {
    var o, e = this,
      p = String(x);
    return p in e && (o = e.__proto__ || e.constructor.prototype, (p in o === false) || e[p] !== o[p])
  });

})(window);

console.log(new_hasOwnProperty('blur'));

1 个答案:

答案 0 :(得分:-1)

发生此错误是因为方法期望Object定义property是否属于此Object

您应该使用以下语法:

Object.hawOwnProperty(property)

在函数需要Object但得到null的地方,您也可能遇到这样的错误。

例如:

Object.keys(null)