什么样子的数据是需要写在原型中?
需要共享的数据就可以写在原型中
原型的作用之一即是:数据共享。
属性需要共享,方法也需要共享
不需要共享的数据写在构造函数中,需要共享的数据写在原型中
function Student(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
//所有学生的身高都是188,所有人的体重都是55
//所有学生都要每天写500行代码
//所有学生每天都要吃一个10斤西瓜
//原型对象
Student.prototype.height='188';
Student.prototype.weight='55kg';
Student.prototype.study=function () {
console.log('学习,写500行代码。');
};
Student.prototype.eat=function () {
console.log('吃一个10斤西瓜。');
};
//实例化对象,并初始化
var Stu = new Student('小光',20,'男');
console.dir(Student);
console.dir(stu);
Stu.eat();
Stu.study();
网友评论