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

相关文章
相关标签/搜索