如视频网站有两种会员:(VIP会员是普通会员,普通会员不是VIP会员)
-
普通会员
-
属性:用户名、密码
-
方法:观看免费视频
-
-
VIP会员
-
属性:普通会员的所有属性、会员到期时间
-
方法:普通会员的所有方法、观看付费视频
-
如果我们需要使用构造函数来创建会员,如何书写构造函数才能实现上面的需求?
// 普通会员的构造函数
function User(username, password){
this.username = username;
this.password = password;
}
User.prototype.playFreeVideo = function(){
console.log('观看免费视频')
}
// VIP会员的构造函数
function VIPUser(username, password, expires){
this.username = username;
this.password = password;
this.expires = expires;
}
VIPUser.prototype.playFreeVideo = function(){
console.log('观看免费视频')
}
VIPUser.prototype.playPayVideo = function(){
console.log('观看付费视频')
}
上面的代码出现了两处重复代码:
-
VIPUser的构造函数中包含重复