Home Web Front-end JS Tutorial Compilation of JavaScript error-prone knowledge points

Compilation of JavaScript error-prone knowledge points

Nov 30, 2017 am 10:52 AM
javascript js Knowledge points

This article is some error-prone knowledge points that I collected and organized during the process of learning JavaScript. It will cover variable scope, type comparison, this pointer, function parameters, and closure. The six aspects of problems, object copying and assignment are introduced and explained from the shallower to the deeper, leading everyone to see clearly the error-prone JavaScript , so that we can write JavaScript code more happily.

JavaScript knowledge points

1. Variable scope

var a = 1;
function test() {
    var a = 2;
    console.log(a); // 2
}
test();
Copy after login

above A is declared and assigned in the function scope , and it is 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();
Copy after login

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 the output is undefined.

var a = 1;
function test3() {
    console.log(a); // 1
    a = 2;
}
test3();
Copy after login

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

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.

function test5() {
    let a = 1;
    {
        let a = 2;
    }
    console.log(a); // 1
}
test5();
Copy after login

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

Comparison of two different arrays above, console is false.

var arr = [],
    arr2 = [];
console.log(arr === arr2); // false
Copy after login

Compare the two identical arrays above. Because two separate arrays are never equal, the console is false.

var arr = [],
arr2 = {};
console.log(typeof(arr) === typeof(arr2)); // true
Copy after login

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

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

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

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

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

4. Function parameters

function test6() {
    console.log(Array.prototype.slice.call(arguments)); // [1, 2]
}
test6(1, 2);
Copy after login

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

function test7 () {
    return function () {
        console.log(Array.prototype.slice.call(arguments)); // 未执行到此,无输出
    }
}
test7(1, 2);
Copy after login

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, [3, 4] will be output.

var args = [1, 2];
function test9() {
    console.log(Array.prototype.slice.call(arguments)); // [1, 2, 3, 4]
}
Array.prototype.push.call(args, 3, 4);
test9(...args);
Copy after login

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('div'); // 如果页面上有5个div
for(var i = 0; i < elem.length; i++) {
    elem[i].onclick = function () {
        alert(i); // 总是5
    };
}
Copy after login

The above is a very common closure problem. The value that pops up when clicking any div is always 5. Because when you trigger the click event, the value of i is already 5, you can solve it in the following way:

var elem = document.getElementsByTagName(&#39;div&#39;); // 如果页面上有5个div
for(var i = 0; i < elem.length; i++) {
    (function (w) {
        elem[w].onclick = function () {
            alert(w); // 依次为0,1,2,3,4
        };
    })(i);
}
Copy after login

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


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

Above we assigned the obj object to the newObj object, thereby changing the name of newObj attribute, but the name attribute of the obj object is also tampered with. This is because the newObj object actually obtains only a memory address, not a real copy, so the obj object is 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;
Copy after login

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

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.

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.

Related recommendations:

javascript object-oriented definition member method instance analysis

Methods for handling JavaScript exceptions

Appearance mode of JavaScript


The above is the detailed content of Compilation of JavaScript error-prone knowledge points. 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles