search
HomeWeb Front-endJS TutorialA compilation of some JavaScript knowledge points that are easy to make mistakes

Preface

This article is some error-prone knowledge points that I collected and organized in the process of learning JavaScript. It will cover variable scope, type comparison, this pointer, and function. The six aspects of parameters, closure issues, and object copying and assignment are introduced and explained from the shallower to the deeper, which also involves some ES6 knowledge points.

JavaScript knowledge points

1. Variable scope

var a = 1;
function test() {
    var a = 2;

    console.log(a); // 2
}

test();

a is declared and assigned in the function scope above , and above the console, so the output a is equal to 2 following the proximity principle.

var a = 1;
function test2() {
    console.log(a); // undefined

    var a = 2;
}

test2();

Although a is declared and assigned in the function scope above, it is located under the console, and the a variable is promoted. It has been declared but has not been assigned a value during output, so "undefined" is output.

var a = 1;
function test3() {
    console.log(a); // 1

    a = 2;
}

test3();

A in the function scope above is reassigned, not re-declared, and is located under the console, so a in the global scope is output.

let b = 1;
function test4() {
    console.log(b); // b is not defined

    let b = 2;
}

test4();

The ES6 let is used in the function scope above to redeclare the variable b. Unlike var, let does not have the function of variable promotion, so the output error "b is not defined" is reported.

function test5() {
    let a = 1;

    {
        let a = 2;
    }

    console.log(a); // 1
}

test5();

In the function scope above, let is used to declare a as 1, and a is declared as 2 in the block-level scope. Because the console is not in the block-level scope within the function, 1 is output. .

2. Type comparison

var arr = [],
    arr2 = [1];

console.log(arr === arr2); // false

Comparison of two different arrays above, console is false.

var arr = [],
    arr2 = [];

console.log(arr === arr2); // false

Comparison of the two identical arrays above, because array-array comparison is always false, so the console is false.

var arr = [],
    arr2 = {};

console.log(typeof(arr) === typeof(arr2)); // true

The above uses typeof to compare arrays and objects. Because typeof obtains NULL, the types of arrays and objects are all object, so the console is true.

var arr = [];

console.log(arr instanceof Object); // true
console.log(arr instanceof Array); // true

The above uses instanceof to determine whether a variable belongs to an instance of an object. Because arrays are also a type of object in JavaScript, both consoles are true.

3.this points to

var obj = {
    name: 'xiaoming',
    getName: function () {
        return this.name
    }
};

console.log(obj.getName());  // 'xiaoming'

This in the object method above points to the object itself, so "xiaoming" is output.

var obj = {
    myName: 'xiaoming',
    getName: function () {
        return this.myName
    }
};

var nameFn = obj.getName;

console.log(nameFn()); // undefined

The method in the object is assigned to a variable above. At this time, this in the method will no longer point to the obj object, but to the window object, so the console is "undefined".

var obj = {
    myName: 'xiaoming',
    getName: function () {
        return this.myName
    }
};

var obj2 = {
    myName: 'xiaohua'
};

var nameFn = obj.getName;

console.log(nameFn.apply(obj2)); // 'xiaohua'

The above also assigns the method in the obj object to the variable nameFn, but points this to the obj2 object through the apply method, so the final console is 'xiaohua'.

4. Function parameters

function test6() {
    console.log(arguments); // [1, 2]
}

test6(1, 2);

The above uses the arguments object in the function to obtain the parameter array passed into the function, so the output array is [1, 2].

function test7 () {
    return function () {
        console.log(arguments); // 未执行到此,无输出
    }
}

test7(1, 2);

The above also uses arguments to obtain parameters, but because test7(1, 2) does not execute the function in return, there is no output. If test7(1, 2)(3, 4) is executed, it will output [ 3, 4].

var args = [1, 2];

function test9() {
    console.log(arguments); // [1, 2, 3, 4]
}

Array.prototype.push.call(args, 3, 4);

test9(...args);

The above uses the Array.prototype.push.call() method to insert 3 and 4 into the args array, and uses the ES6 extension operator (...) to expand the array and pass it into test9, so the console is [ 1, 2, 3, 4].

5. Closure problem

var elem = document.getElementsByTagName('p'); // 如果页面上有5个p

for(var i = 0; i < elem.length; i++) {
    elem[i].onclick = function () {
        alert(i); // 总是5
    };
}

The above is a very common closure problem. The value that pops up when you click on any p is always 5, because when you trigger the click event At that time, the value of i is already 5, which can be solved in the following way:

var elem = document.getElementsByTagName(&#39;p&#39;); // 如果页面上有5个p

for(var i = 0; i < elem.length; i++) {
    (function (w) {
        elem[w].onclick = function () {
            alert(w); // 依次为0,1,2,3,4
        };
    })(i);
}

Encapsulate an immediate execution function outside the bound click event, and pass i into the function.

6. Object copying and assignment

var obj = {
    name: &#39;xiaoming&#39;,
    age: 23
};

var newObj = obj;

newObj.name = &#39;xiaohua&#39;;

console.log(obj.name); // &#39;xiaohua&#39;
console.log(newObj.name); // &#39;xiaohua&#39;

Above we assigned the obj object to the newObj object, thus changing the name attribute of newObj, but the name attribute of the obj object also Tampered, this is because the newObj object actually obtains only a memory address, not a real copy, so the obj object has been tampered with.

var obj2 = {
    name: &#39;xiaoming&#39;,
    age: 23
};

var newObj2 = Object.assign({}, obj2, {color: &#39;blue&#39;});

newObj2.name = &#39;xiaohua&#39;;

console.log(obj2.name); // &#39;xiaoming&#39;
console.log(newObj2.name); // &#39;xiaohua&#39;
console.log(newObj2.color); // &#39;blue&#39;

Using the Object.assign() method above to perform a deep copy of the object can avoid the possibility of the source object being tampered with. Because the Object.assign() method can copy any number of the source object's own enumerable properties to the target object, and then return the target object.

var obj3 = {
    name: &#39;xiaoming&#39;,
    age: 23
};

var newObj3 = Object.create(obj3);

newObj3.name = &#39;xiaohua&#39;;

console.log(obj3.name); // &#39;xiaoming&#39;
console.log(newObj3.name); // &#39;xiaohua&#39;

We can also use the Object.create() method to copy the object. The Object.create() method can create a new object with the specified prototype object and properties.

Conclusion

Learning JavaScript is a long process and cannot be accomplished overnight. I hope that the points introduced in this article can help students learning JavaScript to have a deeper understanding and mastery of JavaScript syntax and avoid detours.

The above is the detailed content of A compilation of some JavaScript knowledge points that are easy to make mistakes. For more information, please follow other related articles on the PHP Chinese website!

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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),