这是因为有两个名称相同的变量
当变量被const替换时,代码会产生错误。我在chrome浏览器控制台中运行此代码。我试着用let初始化变量,但这也产生了一个错误。在问这个问题之前,我已经查看了关于变量的文档,我知道我在这里遗漏了一些关键的东西。
class User {
constructor(email, name){
this.email = email;
this.name = name;
this.score = 0;
}
login(){
console.log(this.email, 'just logged in');
return this;
}
logout(){
console.log(this.email, 'just logged out');
return this;
}
updateScore(){
this.score++;
console.log(this.email, 'score is now', this.score);
return this;
}
}
class Admin extends User {
deleteUser(user){
users = users.filter(u => {
return u.email != user.email
});
}
}
//const userOne = new User ('ryu@ninjas.com', 'Ryu');
var userOne = new User('ryu@ninjas.com', 'Ryu');
var userTwo = new User('yoshi@mariokorp.com', 'Yoshi');
var admin = new Admin('shaun@ninjas.com', 'Shaun');
var users = [userOne, userTwo, admin];
//const users = [userOne, userTwo, admin];
admin.deleteUser(userTwo);
console.log(users);
userOne
。
使用let
和const
,您不能在同一范围内声明多个具有相同名称的变量,但使用var
,它不会重现错误。
此外,因为您正在重新分析用户的常量值,所以使用let
而不是const
声明它
class User {
constructor(email, name){
this.email = email;
this.name = name;
this.score = 0;
}
login(){
console.log(this.email, 'just logged in');
return this;
}
logout(){
console.log(this.email, 'just logged out');
return this;
}
updateScore(){
this.score++;
console.log(this.email, 'score is now', this.score);
return this;
}
}
class Admin extends User {
deleteUser(user){
users = users.filter(u => {
return u.email != user.email
});
}
}
const userOne = new User('ryu@ninjas.com', 'Ryu');
const userTwo = new User('yoshi@mariokorp.com', 'Yoshi');
const admin = new Admin('shaun@ninjas.com', 'Shaun');
let users = [userOne, userTwo, admin];
admin.deleteUser(userTwo);
console.log(users)