原型对象 : prototype
概念:原型对象是构造函数上的一个属性,用来创建公共的方法
原型对象怎么使用? 如何使用原型对象设置公共方法?
//语法: 构造函数.prototype.方法名 = function() {}
function Student(uname) {
this.uname = uname
}
// 设置公共方法
Student.prototype.eat = function () {
console.log('吃饭')
}
let zs = new Student('张三')
let ls = new Student('李四')
console.log(zs.eat === ls.eat) // true
对象原型 __proto__
概念: 对象原型是实例对象(对象)身上的一个属性, 该属性叫 __proto__ (注意: 在谷歌浏览器中 [[prototype]] )
function Student(uname) {
this.uname = uname;
}
//设置公共方法
Student.prototype.eat = function() {
console.log('吃饭');
}
//通过构造函数创建了一个zs 实例对象
let zs = new Student('张三');
zs.eat();
// console.log(zs.__proto__);
// 验证: 对象原型 指向 原型对象
console.log(zs.__proto__ === Student.prototype);
对象原型有什么作用?
作用: 对象原型(__proto__) 默认指向了 原型对象(prototype),导致 实例对象可以调用公共方法
__proto__ 就是实例对象和原型对象之间的一个桥梁
constructor
概念:是原型对象(prototype) 和 对象原型(__proto__)身上的一个属性
作用: constructor会记录当前对象属于哪个构造函数
代码演示:
function Student(uname) {
this.uname = uname
}
// 公共方法
Student.prototype.eat = function () {
console.log('吃饭')
}
console.log('原型对象', Student.prototype)
let zs = new Student('张三')
console.log('对象原型', zs.__proto__)
// 输出:
原型链
概念 : 方法的查找规则 ---> 沿着原型链向上一级查找 (就近原则)
function Student(age) {
this.age = age
}
let zs = new Student(23)
zs.age.toStest()
console.dir(Object);
zs.age.toString();
当前原型对象身上没有 toString() 方法
当前对象身上也么有设置 toString() 方法
为什么可以调用?
原因: 由于原型链存在
原型链:
1. zs 调用 toString()方法的时候,先在当前对象身上查找是否有方法
2. zs 会沿着__proto__ 去 prototype 身上去找
3. Object构造函数就是自定义对象中的老大
window是DOM对象中的老大
Object是自定义对象中的老大