Today in a front-end group, I saw someone posting a question:
var o = new Object();function foo(obj){ var obj = o; obj.name = '123'; obj = new Object(); obj.name = '456'; } foo(o); console.log(o.name)
As shown in the above code, without changing anything In the case of conditions and data, is it possible to output "456"?
It didn’t take long for people in the group to start drawing conclusions, which they couldn’t do under normal circumstances.
The reason? Anyone who knows a little about how to use reference types knows that new Object() changes the point of obj and can never get 456.
It is impossible to output 456 under normal circumstances, so under what error conditions can it be output## Where is #456? After all, programmers are good at writing bugs. They should be able to cause abnormal situations.
Then, my handicapped self suddenly thought of the Proxy I just learned two days ago. We now have a problem when assigning values, so can we solve the problem from metadata? Try it://demo_01var o = new Object(); o = new Proxy(o,{ set(target, key, value,receiver){ if(Object.is('name',key)) return Reflect.set(target, key, `456`,receiver); return Reflect.set(target, key, value , receiver); } })function foo(obj){ var obj = o; obj.name = '123'; obj = new Object(); obj.name = '456'; } foo(o); console.log(o.name)
456.
What? Don't you know what a Proxy is? Click here –> ES6 Interceptor, ProxySo, now is the time to show off the results, and prepare to send them to the group to show off. Let’s look through the chat history first. Hehe, someone has already given an answer faster than me. Okay, let’s take a look at other people’s answers first://demo_02var o = new Object();Object.defineProperty(o,'name',{ set(val){ this.value = '456'; }, get(){ return this.value; } })function foo(obj){ var obj = o; obj.name = '123'; obj = new Object(); obj.name = '456'; } foo(o); console.log(o.name)
//demo_03var o = new Object();function foo(obj){ var obj = o; obj.name = '123'; obj = new Object(); obj.name = '456'; } foo(o); o.name = '456'; console.log(o.name);
So is there any way to solve this problem and achieve real output?
456
I remember that there is a construct method in the Proxy handler. If I can modify its this in the Object constructor. The idea was good, but it failed and didn't come to fruition. If anyone can continue with this idea, please let me know the answer>_<
Checking the chat history, the classmate gave another solution:
var o = new Object();var _Object = Object;Object = function(){ return o; }function foo(obj){ var obj = o; obj.name = '123'; obj = new Object(); obj.name = '456'; } foo(o); console.log(o.name)Object = _Object;
The above is the detailed content of About new, let's start with a BUG. For more information, please follow other related articles on the PHP Chinese website!