Summary of JS important knowledge points (unfinished)

Summary of JS important knowledge points

1. Four ways to query data types

Implementation method typeof instanceof constructor
advantage Easy to use Can detect reference data types Basic ability to detect all types (except null and undefined) All types detected
shortcoming Can only be used for basic data judgment (null will be displayed as Object) Basic types cannot be detected and cannot span iframe constructor is easy to modify and cannot cross iframe IE8 and below, undefined and null are both objects
example typeof str str instanceif String

2. Error type

Error type TypeError ReferenceError ReferenceError instance
explain When referring to null or undefind property 1. When data cannot be queried with RHS in the current scope var a = x; (x not declared)
2. When the target variable cannot be found by using LHS in the current scope (strict mode will not automatically create the variable) a = 3; (a not declared)

3. Judge whether there is certain attribute on the object

method Use (.) or ([] to query in operator hasOwnProperty()
explain By judging the text. Attribute name = = = undefind is equal to that there is no such attribute Value is true when attribute name in textObj exists test.hasOwnProperty The value is true when ('attribute name ') exists
limit This method cannot be used when a property exists but its value is undefind This method can't distinguish itself from the properties on the prototype chain It is applicable to the scene that only judges its own attributes.

4. this points to

Definition: point to the object calling this, this itself is an object, and you can save the relevant values in this function when the function is executed. Its purpose is to use the different points of this to execute this function in different object environments, so as to achieve the reuse effect. In other words, the direction of this is not determined when the function is defined, but confirmed when the function is called, that is, the way the function is called determines the direction of this

this always points to * * [last] [call] its [object]**

Case 1: global call

this points to window

var a = 10
console.log(this.a) // This - > window

Case 2:

function foo() {
function test(fn) {
var a = 20;
var obj = {
    a: 10,
    getA: foo

//so, which is the last call object?
//test -> fn() -> obj.getA ->  foo() -> console.log(this.a)
//Finally, it is called in foo and belongs to window method, so it points to window.
//result  20

Case 3:

//This is an interesting example
var obj = {
    a: 20,
    getA: function() {
        setTimeout(function() {
        }, 1000)

//resul is undefined???
//Now combined with the above sentence, the last call? Who calls setTimeout
//Finally, it is not obj, but window object (because setTimeout is the method of window), so this points to window

Case 4: call and apply

**Call * * and apply belong to Function.prototype Each function instance has call and apply attributes;


The call () method has the same function as the apply () method: change the direction of this.


They differ in the way they receive parameters:
Call(): the first parameter is that the value of this does not change. What changes is that the rest parameters are passed directly to the function. Using call ()
Method, the parameters passed to the function must be listed one by one. Example: call(obj, a,b,c)
Apply(): an array of parameters is passed to the function. Example: apply(obj, [a,b,c])


function add(c, d){ 
    return this.a + this.b + c + d; 
var o = {a:1, b:3};, 5, 7); 			// 1 + 3 + 5 + 7 = 16 this points to o 
add.apply(o, [10, 20]); 	// 1 + 3 + 10 + 20 = 34 this points to o 


  • **The function call of "." * * cannot be found. Its internal this generally points to the window image;

  • **Find the function call with "." *, the internal this generally points to the object to the left of the last ".". If the left side is prototype, find another one to the left;

  • Clearly distinguish whether the function is * * [constructor] or [normal function] * *, and this in [constructor] points to the instantiated object;

  • The function is passed as a parameter. When it is called, its internal this generally points to window.

  • call and apply will change this direction

  • The arrow function of ES6/7 also affects the direction of this

  • In a word, it means "whoever calls me (ordinary function), my internal this points to whom; when I click new (constructor), my internal this points to my instantiation"

5. Functions

6. Data type conversion

Conversion of array, object and string

array --> string

join("+")  // Separate each item of the array with a specified separator;
toString() // Separate each item of the array with commas. The original array remains unchanged

obj --> String

JSON.stringify() // Convert JavaScript objects to strings.

obj --> array

For... in 	// Cyclic assignment
    var arr = []
	for (var i in obj) {
        arr.push(i)		 // attribute
        arr.push(obj[i]) // value
Array.from() // 

string --> array


string --> number

parseFloat('127.1') // Keep decimals
parseInt('123') // Rounding
+number // var c = +'2' // return 2 the return value is number. Other arithmetic methods can also convert strings to numbers

number --> string

var c = number + '' // Add an empty string to convert to string type
var c = String(number) // 
var c = number.toString(8) // Converts number to an octal number, and the type of c is string
var c = number.toFixed(1) // Number to string

number --> array


Deep copy and shallow copy

Shallow copy: B copies A, A changes B (reference data type will change, basic data type will not change)

Deep copy: B copy A, A change B unchanged

Four methods of shallow copy: slice(), concat(), assignment, traversal object.assign ()

// Traversal copy (shallow copy)
var shallowCopy = function(obj) {// Copy only objects (including arrays and objects)if (typeof obj !== 'object' && obj !== null) return;// Judge whether to create an array or an object according to the type of objvar newObj = obj instanceof Array ? [] : {};// Traverse obj and judge that it is the property of obj to copyfor (var key in obj) {if (obj.hasOwnProperty(key)) {
​            newObj[key] = obj[key];}}return newObj;

There are five methods of deep copy: concat, slice and so on JSON.parse(JSON.stringify(arr)), ergodic method, deconstructive evaluation method

Deconstruction assignment method:

const a1 = [1, 2]; const a2 = [...a1];perhapsconst [...a2] = a1;

Ergodic method:

var deepCopy = function(obj) {
    if (typeof obj !== 'object' && obj !== null) return;
    var newObj = obj instanceof Array ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    return newObj;
Merge object methods jquery Ergodic assignment object.assign()
Light copy $.extend(obj1, obj2) object.assign(obj1, obj2)
Deep copy $. Extend (true, obj 1, obj 2), the true attribute needs to be added -
remarks The new object obtained is obj 1, and the properties of obj 2 are copied to obj 1

7. Object properties

The attributes of ES5 include the following six:

  • Configured: indicates whether the attribute can be deleted through delete to redefine the attribute. The attribute can be modified. The default value is true

  • Enumerable: indicates whether properties can be returned through the for in loop. true by default

  • writable: whether the attribute can be modified. The default value is true

  • Value: the data value containing this attribute. When reading the attribute value 3, read from the attribute and when writing the attribute, save the new value to this location. The default value is undefined

  • getter: the function called when the property is read

  • setter: function called when a property is written

Special note: once called Object.defineProperty After the method, the undefined attribute values are undefined except that the configured value is false;

8. Generic event listener

Main appraisal event handlers and event objects and their properties and methods

var EventUtil = {
    addHandler: function(element,type,handler) {//Add event handler
        if(element.addEventListener) {
        } else if(element.attachEvent){
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
    removeHandler:function(element,type,handler) {//Remove event handler
        if(element.removeEventListener) {
    getEvent:function(event){// Get event object
        return event ? event : window.event;
    getTarget:function(event){// Get the target of the event
        return || event.srcElement;
        (event) =>{
            else {event.returnValue= false}
         (event) =>{
            else {event.cancelBubble= true;}
// Real series
var list = document.getElementById('list')
    event= EventUtil.getEvent(ev);
    var target = EventUtil.getTarget(event);

9. ajax Native Writing

var xhr = new XMLHttpRequest();															// 1
xhr.onreadystatechange = function(){													// 2
   if(xhr.readyState == 4){
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status ==304){
           var hh = xhr.responseText;
           var haha1 = document.getElementById('wokao');
           haha1.innerHTML = hh;
}"get","",true);								// 3
xhr.setRequestHeader("Accept", "application/json"); 									// 4
//  xhr.responseType = "json";			
xhr.send(null);																			// 5			

10. Understanding of different HTTP request methods

HTTP request mode

Request method describe
GET Requests the specified page information and returns the entity body
HEAD Similar to get request, but the returned response has no specific content for getting header
POST Submit data to a specified resource for processing requests (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources or the modification of existing resources
PUT The content of the specified document is replaced by data delivered from the client to the server
DELETE Request the server to delete the specified page
CONNECT Reserved in HTTP/1.1 protocol for proxy server that can change connection to pipeline mode
OPTIONS Allow the customer service side to view the performance of the server
TRACE Echo requests received by the server, mainly for testing or diagnosis

HTTP request principle

The HTTP protocol defines how a Web client requests a Web page from a Web server and how the server delivers the Web page to the client. The HTTP protocol uses a request / response model. The client sends a request message to the server, which includes the method, URL, protocol version, request header and request data. The server responds with a status line, including the protocol version, success or error code, server information, response header and response data.

HTTP request / response steps

Keywords: Attribute JSON REST Javascript

Added by jcanker on Thu, 11 Jun 2020 08:26:56 +0300