JavaScript constructor, prototype object, prototype chain, this pointing, error handling

Posted by denniston on Sun, 30 Jan 2022 04:49:12 +0100

catalogue

Constructor

Static and instance members

Prototype object

Prototype chain

Prototype object of access object

Prototype object of prototype object

Prototype chain

this point

error handling

Constructor

Constructors are mainly used to create objects and assign initial values to their members.

//Instantiate object
var p1 = new Person('Zhang San', 18)
var p2 = new Person('Li Si', 19)
console.log(p1.name)   // Output result: Zhang San
console.log(p2.age)   // Output result: 19
p2.sing()             // Output result: I can sing
//Person constructor
function Person(name, age){
    this.name = name;
    this.age = age;
    this.sing = function(){
       console.log('I can sing')
    }
}

Difference between constructor and class:

The member methods in the class are defined in the class. After using the class to create objects, the methods of these objects refer to the same method, which can save memory space

Static and instance members

Instance members refer to members of instance objects, while static members refer to members accessed through classes or constructors.

function Person(uname){
    this.uname = uname
}
Person.school = 'X university';   // Add static property school
Person.sayHello = function(){    // Add static method sayHello
    console.log('Hello')
}
console.log(Person.school)	    // Access static attributes and output results: X University
Person.sayHello();	     // Access the static method and output the result: Hello

Prototype object

Each constructor has a prototype object, which is accessed through the prototype attribute of the constructor.

function Person(){}   // Define function
console.log(Person.prototype)   // Output result: {constructor: ƒ}
console.log(typeof Person.prototype)   // Output result: object

Example: using prototype object sharing method

function Person(uname){
    this.uname = uname
}
Person.prototype.sayHello = function(){
    console.log('Hello, my name is' + this.uname)
}
var p1 = new Person('Zhang San')
var p2 = new Person('Li Si')
console.log(p1.sayHello === p2.sayHello)   // Output result: true
p1.sayHello()   // Output result: Hello, my name is Zhang San
p2.sayHello()   // Output result: Hello, my name is Li Si

Prototype chain

Prototype object of access object

Prototype object of object: each object has one__ proto__ Property, which points to the prototype object of the object.

Relationship between instance object and prototype object:

Constructor to access the object

Constructor of object: there is a constructor attribute in the prototype object, which points to the constructor.

Example: if the prototype object is changed to a new object by assignment, the constructor function cannot be accessed.

//If you modify the prototype object as a new object by assignment, you cannot access the constructor
function Person(){}
    //Modify the prototype object to a new object
    Person.prototype = {
        sayHello:function(){
            console.log("hello")
        }
    }

var p1 = new Person()  //Use the instance object p1 to access the properties in the new prototype object
p1.sayHello()
console.log(p1.constructor)  //The original constructor cannot be accessed using the constructor property
//The constructor property returns a reference to the array function that created this object, so the output is hello

Relationship between constructor, prototype object and instance object

Each constructor has a prototype object. The prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. So what happens if we make the prototype object equal to an instance of another type? Obviously, the prototype object at this time will contain a pointer to another prototype. Accordingly, the other prototype also contains a pointer to another constructor. If another prototype is an instance of another type, the above relationship still holds. In this way, the chain of examples and prototypes is formed. This is the basic concept of the so-called prototype chain. -- from javascript advanced programming

Prototype object of prototype object

Prototype object of prototype object: the prototype object is also an object, so this object should also have a prototype object.

Example: person prototype.__ proto__ This object is actually object Prototype object

function Person(){}
console.log(Person.prototype.__proto__ === Object.prototype)   // true
var obj = {} 
console.log(obj.__proto__ === Object.prototype)   // true
console.log(Object.prototype.__proto__)   // Output result: null

Prototype chain

Structural characteristics of prototype chain

  • Each constructor has a prototype attribute pointing to the prototype object.
  • The prototype object points to the constructor through the constructor property.
  • By instance object__ proto__ Property to access the prototype object.
  • Prototype of Object__ proto__ Property is null.

Prototype chain structure diagram

Structure of function in prototype chain

this point

Analyze this point

  • this inside the constructor points to the newly created object
  • When calling a function directly through the function name, this refers to the global object window.
  • If you call a function as a method of an object, this will point to the object.

Change the method this points to: apply() method and call() method

function method(){
    console.log(this.name)
}
method.apply({ name: 'Zhang San' })	 // Output result: Zhang San
method.call({ name: 'Li Si' })	 // Output result: Li Si

The difference between the apply() method and the call() method:

function method(a, b){
    console.log(a + b)
}
method.apply({}, ['1', '2']) 	// Pass parameters in array mode, output result: 12
method.call({}, '3', '4')		// Parameter transmission mode, output result: 34

error handling

It is usually used when the cause and location of code error cannot be obtained directly.

try{ } catch(e){ }

var o = {}
try{    // Write error prone code in try
   o.func()
   console.log('a')   // If the previous code goes wrong, this line of code will not be executed
} 
catch(e){    // Catch the error in catch, and e represents the error object
   console.log(e)
}
console.log('b')   // If the error has been handled, this line of code will execute

Throw error object

try{
   var e1 = new Error('error message')	// Create error object
   throw e1   // The error object thrown can also be merged with the previous line as: throw new Error('error information ');
} 
catch (e){
   console.log(e.message)	// Output result: error message
   console.log(e1 === e)	// Judge whether e1 and e are the same object, and the output result is true
}

Error type

typeexplain

Error

Represents a common error, and the other six types of error objects inherit from this object

EvalError

Error calling eval() function, which has been discarded. For backward compatibility, lower versions can also be used

RangeError

The value is out of the valid range, such as "new Array(-1)"

ReferenceError

A non-existent variable is referenced, such as "var a = 1; a + b;" (variable b undefined)

SyntaxError

Syntax error in parsing process, such as "{;}" “if()”“var a = new;”

TypeError

A variable or parameter is not of the expected type, such as a function or method that does not exist

URIError

Error in parsing URI encoding, which occurs when calling URI processing functions such as encodeURI() and escape()

Topics: Javascript