Table of Contents
Preface
Here comes the problem
Home Web Front-end JS Tutorial About new, let's start with a BUG

About new, let's start with a BUG

Sep 26, 2017 am 10:30 AM
about


Preface

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)
Copy after login

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.


Here comes the problem

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)
Copy after login

Perfect, successfully outputs

456.

What? Don't you know what a Proxy is? Click here –> ES6 Interceptor, Proxy

So, 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)
Copy after login

Awesome young man, I thought of going together. They are all working on getters and setters, and they are all processing data at the meta level.

This classmate posted an article at the same time, saying that he got inspiration from here. Click here and enjoy it together. It is indeed very well written-> Impeccable hook

Next, I will also post my answer and join in the fun at the time. Wait, some people expressed dissatisfaction and said that he was opportunistic. The demo_02 code is completely equivalent to the demo_03 code:

//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);
Copy after login

When the last line of code "obj.name = '456';" in the demo_02 method is modified, "this.value = '456" in the demo_02 code ';" must also be modified accordingly.

That makes sense. We are indeed taking advantage of opportunities. I wrote demo_01 with the same problem. Fortunately, I didn’t click the Enter key, otherwise I would have been embarrassed.

So is there any way to solve this problem and achieve real output?
456


What does the new operator do?

What is our problem now? The problem is that it is on new Object(), which modifies the this pointer of obj. So is there any way we can avoid it?

What? If you ask me why this pointer has changed, I can only say that you really need to learn JS hard. Take a look at this article. The author's writing style is so interesting. He starts from a soldier and talks about what New has done.

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 = &#39;123&#39;;
    obj = new Object();
    obj.name = &#39;456&#39;;
}

foo(o);
console.log(o.name)Object = _Object;
Copy after login
This time this time The classmate first rewrote the Object object so that it returns the object o. This avoids the change of this point. You are so talented, I admire you. Silently collect<_<


Work hard, there will always be someone who can teach you something

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles