JavaScript之prototype和constructor

2 篇文章 0 订阅

每次创建一个函数,js都会为其添加一个prototype属性,prototype指向该函数的原型对象,原型对象包含可以由特定类型的所有实例共享propertyfunction。而prototype有一个constructor属性,constructor属性指向prototype的拥有者

例如

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属性来判断对象的类型和继承关系是不保险的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值