Please forgive me for asking such unreasonable and irregular questions.
Out of curiosity, I modified the Object.prototype.hasOwnProperty method with the following code, hoping to output the value of the object calling this method.
Code 1
Object.prototype.hasOwnPropertyOld = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = function (data) {
console.log(this);
return this.hasOwnPropertyOld(data);
};
let a = { a: 1, b: 2 };
a.hasOwnProperty("a");
// out:
// {a: 1, b: 2}
// true
a.hasOwnProperty("c");
// out:
// {a: 1, b: 2}
// false
However, the following code seems to cause the page to crash in some cases.
I added a breakpoint for debugging in the Google Chrome Devtool, and did not find out why it crashed, but in the Devtool console, it seems to work normally.(Unfortunately, I can’t provide webpage code that reproduces this problem, but it does happen)
I checked the information and re-modified the Object.prototype.hasOwnProperty method again, see code 2, but it has not been verified at present.
Code 2
let hasOwnPropertyOld = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = function (params) {
console.log(this);
return hasOwnPropertyOld.call(this, params);
};
What kind of situation, what kind of data Code 1 will crash the page?
I think I know the reason, the browser I use may not comply with certain specifications, code 1 in a program's built-in browser, will be stuck, but it is normal in Google Chrome I guess that different browsers execute the above code in different ways, which may lead to a stuck Object.prototype.hasOwnPropertyOld pointing to Object.prototype.hasOwnProperty When running, recursion and endless loops will occur. The following code will also cause a program error
Object.prototype.hasOwnPropertyOld = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = function (data) {
console.log(this);
return this.hasOwnPropertyOld(data);
};
let a = { a: 1, b: 2};
a.hasOwnProperty("a");
// out:
// {a: 1, b: 2}
// true
a.hasOwnProperty("c");
// out:
// {a: 1, b: 2}
// false
let b = {
a: 1,
b: 2,
hasOwnProperty: (data) => {
while (true) {
console.error("error");
}
},
};
b.hasOwnProperty("a");
So I suggest to modify Object.prototype.hasOwnProperty through code 2