如何简单理解js原型链
//实例xu上没有say方法,会顺着原型链向上查找,构造函数上包含say方法,成功调用
//__proto__是每个对象都有的属性,xu不是函数,没有prototype,构造函数Person包含prototype
//__proto__可以理解为“构造器的原型”,即__proto__===constructor.prototype
// 构造函数
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.say = function () {
//this是什么要看执行的时候谁调用了这个函数。
console.log("I'm " + this.name + " And I'm " + this.age)
}
const xu = new Person('徐同保', 30)
xu.say() //I'm 徐同保 And I'm 30
console.log(xu.say === xu.__proto__.say) //true
console.log(xu.__proto__ === Person.prototype) //true
console.log(xu.say === Person.prototype.say) //true
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步