简单介绍
1 class关键字,构造器和类分开了
1.1 ES5代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES5旧方法</title>
<script>
function User(name, pass) {
this.name = name;
this.pass = pass;
}
User.prototype.showName = function() {
alert(this.name);
};
User.prototype.showPass = function() {
alert(this.pass);
};
let user = new User("blue", "123456");
user.showName();
user.showPass();
</script>
</head>
<body>
</body>
</html>
1.2 ES6代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6新方法</title>
<script>
class User {
constructor(name, pass) {
this.name = name;
this.pass = pass;
}
showName() {
alert(this.name);
};
showPass() {
alert(this.pass);
};
}
let user = new User("blue", "123456");
user.showName();
user.showPass();
</script>
</head>
<body>
</body>
</html>
2.class里面直接加方法,简化继承核心
2.1 ES5代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES5继承</title>
<script>
function User(name, pass) {
this.name = name;
this.pass = pass;
}
User.prototype.showName = function() {
alert(this.name);
};
User.prototype.showPass = function() {
alert(this.pass);
};
// let user = new User("blue", "123456");
// user.showName();
// user.showPass();
// -----继承
function VipUser(name, pass, level) {
User.call(this, name, pass);
this.level = level;
};
VipUser.prototype = new User();
VipUser.prototype.constructor = VipUser;
VipUser.prototype.showLevel = function() {
alert(this.level);
};
let user1 = new VipUser("blue", "123456", '3');
user1.showName();
user1.showPass();
user1.showLevel();
</script>
</head>
<body>
</body>
</html>
2.2 ES6代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6新方法</title>
<script>
class User {
constructor(name, pass) {
this.name = name;
this.pass = pass;
}
showName() {
alert(this.name);
};
showPass() {
alert(this.pass);
};
}
// let user = new User("blue", "123456");
// user.showName();
// user.showPass();
class VipUser extends User {
constructor(name, pass, level) {
super(name, pass);
this.level = level;
}
showLevel() {
alert(this.level);
}
}
let user1 = new VipUser("blue", "123456", '3');
user1.showName();
user1.showPass();
user1.showLevel();
</script>
</head>
<body>
</body>
</html>