ES5构造函数和继承:
// ES5构造函数
function User(name, pass) {
this.name = name;
this.pass = pass;
}
User.prototype.showName = function() {
console.log(this.name);
}
User.prototype.showPass = function() {
console.log(this.pass);
}
var u1 = new User('Guofq', 123123);
u1.showName();
u1.showPass();
// ES5继承
function Vipuser(name, pass, level) {
console.log(this);
User.apply(this, [name, pass]);
this.level = level;
}
Vipuser.prototype = new User();
Vipuser.prototype.constructor = Vipuser;
Vipuser.prototype.showLevel = function() {
console.log(this.level);
}
var v1 = new Vipuser('Zhangs', 123123, 12);
v1.showName();
v1.showPass();
v1.showLevel();
ES6构造函数和继承:
// ES6构造函数
class User2 {
constructor(name, pass) {
this.name = name;
this.pass = pass;
}
showName() {
console.log(this.name);
}
showPass() {
console.log(this.pass);
}
}
let u2 = new User2('Lis', 123456);
u2.showName();
u2.showPass();
// ES6继承
class Vipuser2 extends User2 {
constructor(name, pass, level) {
super(name, pass);
this.level = level;
}
showLevel() {
console.log(this.level);
}
}
let v2 = new Vipuser2('Wangw', 12345678, 6);
v2.showName();
v2.showPass();
v2.showLevel();
网友评论