构造函数(类)有原型对象,其实就是构造函数身上的一个自带属性,这个属性是:prototype
对象也有原型对象,其实就是对象身上的一个自带属性,这个属性是:__proto__
所有同类型的对象身上的原型对象属性,都指向类的原型对象属性。类和对象的原型对象身上挂的方法,对象可以直接使用,不需要经过原型对象。如果将方法直接定义在类里面,将来根据这个类创建的每个对象,都要创建自己独立的这些方法, 如果要创建很多对象,对内存的开销会很大。 我们可以将类的方法,添加到类的原型对象身上
Student.prototype.sayHi = function(){
console.log(`Hi!我叫${this.name},今年${this.age}岁,性别是${this.sex}`);
}
Student.prototype.study = function(time){
console.log(`Hi!我叫${this.name},我每天学习${time}小时`);
}
Student.prototype.play = function(time){
console.log(`Hi!我叫${this.name},我每天玩${time}小时`);
}
let s1 = new Student('张三',20,'男')
let s2 = new Student('李四',22,'女')
let s3 = new Student('王五',24,'男')
// 查了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)
s2.sayHi()
s2.study(6)
s2.play(6)
s3.sayHi()
s3.study(10)
s3.play(1)