The constructor and prototype javascript

Each time a function is created, js will be to add a prototypeproperty, the prototype of the prototype object point function, comprising a prototype object may be shared by all instances of a particular type of propertyand function. And prototypethere is a constructorproperty, constructorattribute points to prototypethe owner

E.g

function Person(name) {
  this.name = name;
}
Person.prototype.getName = function() {
  return this.name
}
Person.prototype.parents = ['father', 'mother']
let person1 = new Person('Jack');
let person2 = new Person('Tim');
console.log(person1.getName());  // Jack
console.log(person2.getName());  // Iim
console.log(person1.getName === person2.getName);  // true
console.log(Person.prototype);  // Person { getName: [Function], parents: [ 'father', 'mother' ] }
console.log(Person.prototype.constructor);  // [Function: Person]
复制代码

In the section of code Personis a particular type of object, but person1, person2all Personthe examples, Personthere are two property: nameand parents, 1 function: getName. Shared by these two examples property: parentssharing getNamemethod: , Personthe prototypepoint Personprototype object, Personthe prototype object contains property: parentscomprising the function: getName; Personis prototypethere a constructorproperty, costructorattribute points to Personthe function. And constructora modifiable attributes

function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name
};

function Teacher(name) {
    this.name = name;
}
function SpecialPerson() {

}
Teacher.prototype = new Person();
Teacher.prototype.constructor = SpecialPerson;
let teacher1 = new Teacher('Mr.Li');
console.log(Teacher.prototype.constructor);  // [Function: SpecialPerson]
console.log(teacher1.constructor);  // [Function: SpecialPerson]
console.log(teacher1 instanceof Teacher)  // true
console.log(teacher1 instanceof Person);  // true
console.log(teacher1 instanceof SpecialPerson);  // false
复制代码

Therefore, by constructorjudging object attribute types and inheritance are not insurance

Reproduced in: https: //juejin.im/post/5cf9ce2c5188251c06481e34

Guess you like

Origin blog.csdn.net/weixin_34092370/article/details/91454822