原型对象
// 构造函数(类)有原型对象,其实就是构造函数身上的一个自带的属性,这个属性是prototype
// 对象也有原型对象,其实就是睡醒身上的一个自带属性,这个属性是_proto_
// 所有同类型的对象,身上的原型对象属性都指向类的原型对象属性
function students(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
// 如果将方法直接定义在类里面,将来根据这个类创建的每个对象都有创建自己独立的这些方法
// 如果要创建很多对象,对内存的开销很大
/* this.sayHi = function () {
console.log(`我叫${this.name}今年${this.age}岁,性别是${this.sex}`);
}
this.study = function (time) {
console.log(`我叫${this.name},我每天学习${time}小时`);
}
this.play = function (time) {
console.log(`我叫${this.name},我每天玩${time}小时`);
} */
}
// 我们可以将类的方法,添加在类的原型对象身上
students.prototype.sayHi = function () {
console.log(`我叫${this.name}今年${this.age}岁,性别是${this.sex}`);
}
students.prototype.study = function (time) {
console.log(`我叫${this.name},我每天学习${time}小时`);
}
students.prototype.play = function (time) {
console.log(`我叫${this.name},我每天玩${time}小时`);
}
let s1 = new students('张三',20,'男')
let s2 = new students('李四',22,'女')
let s3 = new students('王五',25,'男')
// 查了Student类的原型对象
// console.log(Student.prototype);
// 查看三个对象的原型对象 -- 你会发现,长得一样。
// console.log(s1.__proto__);
// console.log(s2.__proto__);
// console.log(s3.__proto__);
s1.sayHi()
s1.study(8)
s1.play(3)
console.log('------------------');
s2.sayHi()
s2.study(6)
s2.play(6)
console.log('------------------');
s3.sayHi()
s3.study(10)
s3.play(1)