对象javascript没有内置函数hasOwnProperty

Object javascript dont have build-in function hasOwnProperty

本文关键字:函数 hasOwnProperty 内置 javascript 对象      更新时间:2023-09-26

我的代码

console.log(typeof res.locals);
console.log(res.locals.hasOwnProperty('a'));

我的结果:

object
Unhandled rejection TypeError: res.locals.hasOwnProperty is not a function

注1:res为响应对象;

我使用Express 4.13.3 .有人知道这里有什么问题吗?

注意:

  var a = Object.create(null);
  var b = {};
  a.hasOwnProperty('test');
  b.hasOwnProperty('test');

我在这里发现bug Object.create(null)不使Object javascript与内置函数

res.locals在Express中被定义为没有原型的对象:

res.locals = res.locals || Object.create(null);

通过传递null,对象不继承任何属性或方法,包括Object.prototype上的属性或方法,如hasOwnProperty

console.log(Object.getPrototypeOf(res.locals)); // null
console.log(Object.create(null) instanceof Object); // false

要对res.locals使用该方法,您必须通过Object.prototype:

访问它。
console.log(Object.prototype.hasOwnProperty.call(res.locals, 'a'));
// or store it
var hasOwnProperty = Object.prototype.hasOwnProperty;
console.log(hasOwnProperty.call(res.locals, 'a'));