Common JavaScript error-prone knowledge points

Source: Internet
Author: User
This article describes some error-prone knowledge points that I have collected and sorted out during the JavaScript process. They will be divided into variable scopes, type comparisons, this points to, function parameters, the six aspects of closure and object copy and assignment are introduced and explained in a simple way. Some ES6 knowledge points are also involved. 1. variable scope

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

In the function scope above, a is declared and assigned a value, and it is placed on the console. Therefore, output a equals to 2 according to the proximity principle.

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

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

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

In the function scope above, a is re-assigned, not re-declared, and is under the console. Therefore, a in the global scope is output.

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

In the function scope above, let of ES6 is used to re-declare variable B. let is different from var in that it does not have the function of variable escalation. Therefore, the output reports "B is not defined ".

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

In the function scope above, let declares that a is 1, and declares that a is 2 in the block-level scope. Because the console is not in the block-level scope of the function, output 1.

2. Type comparison

var arr = [],     arr2 = [1]; console.log(arr === arr2); // false

Compare two different arrays on the top, and set console to false.

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

Compare the two identical arrays above. Because the two independent arrays are never equal, 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, arrays, and objects of all types, 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 in JavaScript are also an object, both consoles are true.

3. this points

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

This in the above object method 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. In this case, this in the method no longer points to the obj object and thus to the window object. Therefore, 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 method in the obj object is also assigned to the nameFn variable, but this is directed to the obj2 object through the apply method. Therefore, the 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 input function parameter array, so the output array is [1, 2].

Function test7 () {return function () {console. log (arguments); // No output} test7 (1, 2 );

Parameters are also obtained using arguments, but no output is generated because test7 (1, 2) does not execute the function in return. If test7 (1, 2) (3, 4) is executed) the output is [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 upper part uses the Array. prototype. push. call () method to insert 3 and 4 to the args Array, and uses the ES6 extension operator (...) Expand the array and input test9, so the console is [1, 2, 3, 4].

5. Closure Problems

Var elem = document. getElementsByTagName ('P'); // if there are 5 p for (var I = 0; I <elem. length; I ++) {elem [I]. onclick = function () {alert (I); // always 5 };}

The top is a very common closure problem. the pop-up value of clicking any p is always 5, because when you trigger a click event, the I value is already 5, which can be solved in the following way:

Var elem = document. getElementsByTagName ('P'); // if there are 5 p for (var I = 0; I <elem. length; I ++) {(function (w) {elem [w]. onclick = function () {alert (w); // values: 0, 1, 2, 3, 4 };}) (I );}

Encapsulate an immediate execution function outside the bound Click Event and pass I to the function.

6. Object copy and assignment

var obj = {     name: 'xiaoming',     age: 23 };  var newObj = obj; newObj.name = 'xiaohua'; console.log(obj.name); // 'xiaohua' console.log(newObj.name); // 'xiaohua'

In the above section, we assigned the obj object to the newObj object to change the name attribute of newObj. However, the name attribute of the obj object is also tampered with because the newObj object actually only obtains a memory address, instead of the actual copy, the obj object is tampered.

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'

The above method uses Object. assign () to perform Object deep copy to avoid the possibility of source Object tampering. Because the Object. assign () method can copy the enumerated attributes of any source Object to the target Object, and then return the target Object.

var obj3 = {     name: 'xiaoming',     age: 23 }; var newObj3 = Object.create(obj3); newObj3.name = 'xiaohua'; console.log(obj3.name); // 'xiaoming' console.log(newObj3.name); // 'xiaohua'

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

Conclusion

Learning JavaScript is a long process and cannot be achieved overnight. I hope that the content introduced in this article will help students who want to learn JavaScript more deeply understand and master the JavaScript syntax, so as to avoid detours.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.