javascript之constructor與prototype

每次建立一個函數,js都會爲其添加一個prototype屬性,prototype指向該函數的原型對象,原型對象包含能夠由特定類型的全部實例共享propertyfunction。而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有兩個propertynameparents,有1個functiongetName。這兩個實例共享的propertyparents,共享的方法:getNamePersonprototype指向Person的原型對象,Person的原型對象包含的propertyparents,包含的functiongetNamePersonprototype有一個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

相關文章
相關標籤/搜索