1.ES5创建类
function User(name, age) {
this.name = name;
this.age = age;
}
// 静态方法
User.getClassName = function () {
return 'User';
}
User.prototype.changeName = function (name) {
this.name = name;
}
User.prototype.changeAge = function (age) {
this.age = age;
}
Object.defineProperty(User.prototype, 'info', {
get() {
return 'name:' + this.name + ' | age:' + this.age;
}
});
/* var user = new User('lucky',30);
console.log(user.info); */
// 定义子类
function Manager(name,age,password) {
User.call(this,name,age);
this.password =password;
}
// 继承静态方法
Manager.__proto__ = User;
// 继承prototype方法
Manager.prototype = User.prototype;
// 添加新方法
Manager.prototype.changePassword = function(password){
this.password = password;
}
var m = new Manager('xxxx',30,'123');
console.log(m.name);
m.changeName('yyyy')
console.log(m.name);
console.log(m.info);
1.ES6创建类
'use strict'
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 静态方法
static getClassName() {
return 'User';
}
changeName(name) {
this.name = name;
}
// 定义属性info
get info() {
return 'name:' + this.name + ' | age:' + this.age;
}
}
// 定义子类
class Manager extends User {
constructor(name, age, password) {
super(name, age);
this.password = password;
}
changePassword(password) {
this.password = password;
}
// 覆盖父类info
get info() {
let info = super.info;
console.log(info);
return 'new info ------';
}
}
// let m = new Manager('baby',6,'123456');
// console.log(m.info);
// 对象没有提升
//let em = new Employee('eeee',11);//出错
class Employee extends User {
// 默认自动加入constructor
// constructor(...args){
// super(...args);
// }
}
// let e = new Employee('zhangsan',20);
// console.log(e.info);
// 立即执行类"实例化"
// let customer = new class Customer {
// constructor(name) {
// this.name = name;
// }
// }('lisi');
// console.log(customer);
网友评论