什么是原型对象?
概念: 是构造函数中的一个属性,该属性叫 prototype
代码演示:
function Student(uname) {
this.uname = uname
this.eat = function () {
console.log('吃饭')
}
}
console.log(Student.prototype);
原型对象有什么作用?
作用: 通过原型对象给构造函数设置公共方法
首先验证构造函数中的方法到底是不是公共的?
结合上下文通过构造函数创建两个对象
let zs = new Student('张三');
let ls = new Student('李四');
console.log(zs.eat === ls.eat); 结果为 false
原型对象怎么使用? 如何使用原型对象设置公共方法?
语法: 构造函数.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