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);
添加回答
舉報