每次建立一个函数,js都会为其添加一个
prototype
属性,prototype指向该函数的原型对象,原型对象包含能够由特定类型的全部实例共享的property
和function
。而prototype
有一个constructor
属性,constructor
属性指向prototype
的拥有者javascript
例如java
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]
复制代码
上一段代码中Person
就是一个特定类型的对象,而person1
,person2
都是Person
的实例,Person
有两个property
:name
和parents
,有1个function
:getName
。这两个实例共享的property
:parents
,共享的方法:getName
,Person
的prototype
指向Person
的原型对象,Person
的原型对象包含的property
:parents
,包含的function
:getName
;Person
的prototype
有一个constructor
属性,costructor
属性指向Person
这个函数。而constructor
是一个可修改的属性函数
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
复制代码
所以经过constructor
属性来判断对象的类型和继承关系是不保险的ui