坏蛋格鲁坏蛋格鲁

【Javascript】ES5 完美方案实现类的继承

    1. 基础模式
function Parent(name) {
    this.name = name;
}
Parent.prototype.sayHello = function () {
    console.log('Hello, ' + this.name);
}

function Child(name, age){
    Parent.call(this, name);
    this.age = age
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

let c1 = new Child("Cname1", 18);
let c2 = new Child("Cname2", 24);

console.log(c1.name);
console.log(c2.name);
c1.sayHello();
c2.sayHello();
    1. 圣杯模式

function Parent() {
    this.lastName = "Deng";
}

function Child() {}

function F() {}
F.prototype = Father.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;

const c = new Child();
console.log(c.lastName); // 输出 "Deng"

Child.prototype.sex = "male";
console.log(c.sex); // 输出 "male"
    1. 现代简易模式
function Parent(username) {
    this.username = username;
}
Parent.prototype.say = function() {
    console.log('Parent Say Hello');
}

function Child(username, age) {
    Parent.call(this, username);
    this.age = age;
}
Child.prototype.run = function() {
    console.log('Child Run');
}

Object.setPrototypeOf(Child.prototype, Parent.prototype)

const p = new Parent('wang');
console.log(p.username);
p.say();

const c = new Child('wangchong', 22);
console.log(c.username);
console.log(c.age);
c.say();
c.run();
本原创文章未经允许不得转载 | 当前页面:坏蛋格鲁 » 【Javascript】ES5 完美方案实现类的继承

评论