gpt4 book ai didi

javascript - javascript对象没有内置函数hasOwnProperty

转载 作者:行者123 更新时间:2023-12-03 08:46:11 24 4
gpt4 key购买 nike

这是我的代码

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的响应对象;

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

注意:

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

我在这里发现错误 Object.create(null) 不要使用内置函数创建对象 javascript

最佳答案

res.locals is defined in Express作为没有原型(prototype)的对象:

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'));

关于javascript - javascript对象没有内置函数hasOwnProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com