Each time a function is created, js will be to add a
prototype
property, the prototype of the prototype object point function, comprising a prototype object may be shared by all instances of a particular type ofproperty
andfunction
. Andprototype
there is aconstructor
property,constructor
attribute points toprototype
the 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 Person
is a particular type of object, but person1
, person2
all Person
the examples, Person
there are two property
: name
and parents
, 1 function
: getName
. Shared by these two examples property
: parents
sharing getName
method: , Person
the prototype
point Person
prototype object, Person
the prototype object contains property
: parents
comprising the function
: getName
; Person
is prototype
there a constructor
property, costructor
attribute points to Person
the function. And constructor
a 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 constructor
judging object attribute types and inheritance are not insurance
Reproduced in: https: //juejin.im/post/5cf9ce2c5188251c06481e34