一、ES5
function Person (name, age) {
// 添加属性
this.name = name;
this.age = age;
}
// 添加方法
Person.prototype.showName = function () {
console.log(this.name);
}
Person.prototype.showAge = function () {
console.log(this.age);
}
// 继承
function Worker (name, age, job) {
Person.call(this, name, age);
this.job = job;
}
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;
Worker.prototype.showJob = function () {
console.log(this.job);
}
let w = new Worker('Tom', 23, '教师');
w.showName();
w.showAge();
w.showJob();
二、ES6
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
showName() {
console.log(this.name);
}
showAge() {
console.log(this.age);
}
// 静态方法 类似于 Array.from()只能在原型对象上调用的方法
static description() {
console.log(`I am a man`)
}
set address(value) {
this.addressInfo = value;
}
get address() {
return `I from ${this.addressInfo}`
}
}
let p = new Person('Jack', 14);
p.showName();
p.showAge();
Person.description(); // I am a man
p.address = 'ShanDong';
p.address // I from ShanDong
//继承
class Worker extends Person {
constructor(name, age, job) {
super(name, age);
this.job = job;
}
showJob() {
console.log(this.job);
}
}
let w = new Worker('Tony', 26, '工程师');
w.showName();
w.showAge();
w.showJob();
网友评论