search
HomeWeb Front-endJS TutorialTalk about the problems caused by using consecutive assignment operations in javascript_javascript skills

Foreword

This sentence in the title of the article was originally seen in a foreign JavaScript specification. At that time, it did not attract enough attention until a bug recently discovered the characteristics (pitfalls) of the continuous assignment operation in JS.

After searching online, I found a very good example of continuous assignment (source 1, source 2):

var a = {n:1};
a.x = a = {n:2};
console.log(a.x); // 输出?

The answer is:

console.log(a.x); // undefined

I don’t know if you got the answer right, at least I got it wrong.

So I took this opportunity to take a closer look at how JS continuous assignment works

Assignment order?

Suppose there is a code: A=B=C; , the execution order of assignment statements is from right to left, so the problem is:

Is conjecture 1: B = C; A = C; ?

Or guess 2: B = C; A = B; ?

We all know that if two objects point to an object at the same time, then the modification to this object is synchronized, such as:

var a={n:1};
var b=a;
a.n=2;
console.log(b);//Object {n: 2}

So you can test the order of consecutive assignments based on this feature.

According to conjecture 1, replace C with a specific object. You can see that the modification of a will not be synchronized to b, because two {n:1} are created when the first and second lines are executed. object. Such as:

var b={n:1};
var a={n:1};
a.n=0;
console.log(b);//Object {n: 1}

According to conjecture 2, replace C with a specific object. You can see that the modification of a is synchronized to b, because a and b refer to an object at the same time, such as:

var b={n:1};
var a=b;
a.n=0;
console.log(b);//Object {n: 0}

Testing true continuous assignment:

var a,b;
a=b={n:1};
a.n=0;
console.log(b);//Object {n: 0}

You can see that it is consistent with conjecture 2. If anyone feels that this test is inaccurate, you can test it again and use the setter and getter features of ECMA5 to test.

First of all, setters and getters are applied to variable names, not the objects actually stored in the variables, as follows:

Object.defineProperty(window,"obj",{
 get:function(){
  console.log("getter!!!");
 }
});
var x=obj;
obj;//getter!!! undefined
x;//undefined

You can see that only obj outputs "getter!!!", but x does not. Use this feature to test.

Continuous assignment test 2:

Object.defineProperty(window,"obj",{
 get:function(){
  console.log("getter!!!");
 }
});
a=b=obj;//getter!!! undefined

Confirmed again through getter, in A=B=C, C is only read once.

So, the real operation rule of continuous assignment is B = C; A = B; That is, continuous assignment always takes only the expression result on the right side of the equal sign from right to left and assigns it to the left side of the equal sign.

Can continuous assignment be written separately?

You can see the real rules of continuous assignment from the above. Then return to the case at the beginning of the article. If you split the continuous assignment according to the above rules, you will find that the result is different, such as:

var a={n:1};
a={n:2};
a.x=a;
console.log(a.x);//Object {n: 2, x: Object}

So although the continuous assignment statement follows the rules of assignment from right to left, it still cannot be written in separate statements. As for why

I guess: In order to ensure the correctness of the assignment statement, js will first take out a copy of all the reference addresses to be assigned before executing an assignment statement, and then assign values ​​one by one.

So I think the logic of this code a.x=a={n:2}; is:

1. Before execution, the reference addresses of a in a and a.x will be taken out first. This value points to {n:1}

2. Create a new object {n:2} in memory

3. Execute a={n:2} and change the reference of a from pointing to {n:1} to pointing to the new {n:2}

4. Execute a.x=a. At this time, a already points to the new object, and because a.x retains the original reference before execution, a.x’s a still points to the original {n:1} object, so the new object is given to the original object. Add an attribute x with the content {n:2}, which is now a

5. The statement execution ends, the original object changes from {n:1} to {n:1,x:{n:2}}, and the original object is recycled by GC because no one references it anymore. Currently a Point to new object {n:2}

6. So we have the running result at the beginning of the article, and then execute a.x, it will naturally be undefined

The above process is illustrated by serial number:

Following the above process, it can be seen that the old a.x and the new a both point to the newly created object {n:2}, so they should be congruent.

Test:

var a = {n:1};
var b = a;
a.x = a = {n:2};
console.log(a===b.x); //true

Because we added var b=a, which means adding a reference to the original object, it will not be released in step 5 above, which confirms the above conclusion.

Postscript

Through this time, I learned about the characteristics of continuous assignment. Looking back at the title of the article, it seems that it should be called:

Try not to use JS’s continuous assignment operation unless you really understand its internal mechanism and possible consequences.

Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools