1 回答
TA贡献1887条经验 获得超5个赞
如果不被篡改,则差异相对较小。但是,如果您依赖于包含原型函数,那么各种各样的东西都会妨碍您期望它工作(甚至可能是偶然的)。这就是为什么您经常会看到库直接调用原型方法,而不是依赖于它们对单个对象的完整性。objobj
请考虑以下情况:
const prop = 'test';
obj = {test: 'example'};
console.log({
'version': 'no tampering!',
'obj.hasOwnProperty': obj.hasOwnProperty(prop),
'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});
// someone does something you don't expect with obj
obj.hasOwnProperty = () => false;
// NOTE: This at least is a function, there is nothing to stop me from setting it to something that would BREAK the function call...
// E.g. obj.hasOwnProperty = 42;
console.log({
'version': 'some tampering!',
'obj.hasOwnProperty': obj.hasOwnProperty(prop),
'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});
或者,如果 对象不继承原型呢?objObject
const obj = Object.create(null);
console.log(obj.hasOwnProperty);
添加回答
举报