Preface
This article is about some error-prone knowledge points that I collected and organized in the process of learning JavaScript. It will focus on variable scope, type comparison, this pointer, function parameters, closure issues and object copying and The six aspects of 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 it is above the console, so the output follows the proximity principle a is equal to 2.
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 the comparison between arrays and arrays 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);
上方利用Array.prototype.push.call()方法向args数组中插入了3和4,并利用ES6延展操作符(…)将数组展开并传入test9,所以console为[1, 2, 3, 4]。
5.闭包问题
var elem = document.getElementsByTagName('div'); // 如果页面上有5个div for(var i = 0; i < elem.length; i++) { elem[i].onclick = function () { alert(i); // 总是5 }; }
上方是一个很常见闭包问题,点击任何div弹出的值总是5,因为当你触发点击事件的时候i的值早已是5,可以用下面方式解决:
var elem = document.getElementsByTagName('div'); // 如果页面上有5个div for(var i = 0; i < elem.length; i++) { (function (w) { elem[w].onclick = function () { alert(w); // 依次为0,1,2,3,4 }; })(i); }
在绑定点击事件外部封装一个立即执行函数,并将i传入该函数即可。
6.对象拷贝与赋值
var obj = { name: 'xiaoming', age: 23 }; var newObj = obj; newObj.name = 'xiaohua'; console.log(obj.name); // 'xiaohua' console.log(newObj.name); // 'xiaohua'
上方我们将obj对象赋值给了newObj对象,从而改变newObj的name属性,但是obj对象的name属性也被篡改,这是因为实际上newObj对象获得的只是一个内存地址,而不是真正 的拷贝,所以obj对象被篡改。
var obj2 = { name: 'xiaoming', age: 23 }; var newObj2 = Object.assign({}, obj2, {color: 'blue'}); newObj2.name = 'xiaohua';console.log(obj2.name); // 'xiaoming' console.log(newObj2.name); // 'xiaohua' console.log(newObj2.color); // 'blue'
上方利用Object.assign()方法进行对象的深拷贝可以避免源对象被篡改的可能。因为Object.assign() 方法可以把任意多个的源对象自身的可枚举属性拷贝给目标对象,然后返回目标对象。
var obj3 = { name: 'xiaoming', age: 23 }; var newObj3 = Object.create(obj3); newObj3.name = 'xiaohua';console.log(obj3.name); // 'xiaoming' console.log(newObj3.name); // 'xiaohua'
我们也可以使用Object.create()方法进行对象的拷贝,Object.create()方法可以创建一个具有指定原型对象和属性的新对象。
结语
学习JavaScript是一个漫长的过程,不能一蹴而就。希望本文介绍的几点内容能够帮助学习JavaScript的同学更加深入的了解和掌握JavaScript的语法,少走弯路。
以上就是JavaScript易错知识点整理的内容,更多相关内容请关注PHP中文网(www.php.cn)!

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.

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.

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.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
