JavaScript is an object-based language. Unlike object-oriented languages, functions are also objects, and constructors can be considered a special class. Any function has a Prototype property

prototype

  • Prototype gets an object that has the constructor property and the function name.prototype.constructor gets the function
  • The constructor’s prototype is the prototype of the instance
  • Add methods to the constructor’s Prototype so that instance objects created from new can call the same method in memory to avoid wasting memory

Prototype chain search

  • An instance object can access properties and methods of its prototype through the dot
    function People(name, age) {... }; People.prototype.sex ="Male";
    let xiaoming = new People("Xiao Ming".12);
    console.log(xiaoming.sex);		/ / "male"
    Copy the code
  • The hasOwnProperty method checks whether an object actually owns a property or method
    xiaoming.hasOwnProperty("name");	// true
    xiaoming.hasOwnProperty("age");		// true
    xiaoming.hasOwnProperty("sex");		// false
    Copy the code
  • The in method checks if a property or method is accessible by an object, not if it is its own property or method
    "name" in xiaoming;		// true
    "age" in xiaoming		// true
    "sex" in xiaoming		// fasle
    Copy the code

The end of the prototype chain

  • All objects in javascript can be thought of as instance objects created by the Object class through New. Object is the end of the prototype chain for all instance objects
    function People() {... };let xiaoming = new People();
    console.log(xiaoming.__proto__.__proto__ === Object.prototype);	// true
    console.log(Object.prototype.__proto__);		// null
    Copy the code

inheritance

  • Inheritance is implemented using javascript-specific prototype chains
    // Create a parent class
    function People(name, age) {... };// Create a subclass
    function Student(name, age, sex) {... };// Implement inheritance, since the constructor's prototype is the prototype of the instance object, mount the parent class's instance object to the prototype of the subclass
    Student.prototype = new People();
    Copy the code