每次建立一個函數,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