一个javascript prototype继承问题

查看:100
本文介绍了一个javascript prototype继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

一个javascript prototype继承问题,问题已经解决。

解决方案

至于为什么报错:

var ph = new phh();
phh.prototype = person.prototype;

用构造器构造新对象时,新对象的原型指向当前构造器的原型,如果之后构造器的原型被指向其它对象,这一修改不会在已经构造的对象上有所体现。只有在原地修改对象时(不改变引用,只增添/修改/删除属性时)才会体现出来。

显然在构建 ph 的时候,构造器的原型 phh.prototype 还指向默认值,所以构造出的 ph 就不以 person 为原型了。

ph.__proto__ !== phh.prototype // true

调整下顺序

phh.prototype = person.prototype;
var ph = new phh();
    
ph.__proto__ === phh.prototype // true

顺便,
帮你重构了一下

function Person(name, age) {
    this.name = name;
    this.age = age;
}

function Coder(name, age, job) {
    Person.call(this, name, age);
    this.job = job;
}
Person.prototype.greet = function() {
    console.log("My name is " + this.name);
}

function Phh() {};

Phh.prototype = Person.prototype;
Coder.prototype = new Phh();
Coder.prototype.constructor = Coder;
Coder.prototype.intro = function() {
    console.log("My job is " + this.job);
}

var p = new Person("Leo", 32);
p.greet();
var v = new Coder("Momo", 23, "Coding");
v.greet();
v.intro();

继续重构:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log("My name is " + this.name);
    }
}

class Phh extends Person {}

class Coder extends Phh {
    constructor(name, age, job) {
        super(name, age);
        this.job = job;
    }
    intro() {
        console.log("My job is " + this.job);
    }
}

var p = new Person("Leo", 32);
p.greet();
var v = new Coder("Momo", 23, "Coding");
v.greet();
v.intro();

进一步重构:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log("My name is " + this.name);
    }
}

class Phh extends Person {
    constructor(name, age, job) {
        super(name, age);
        this.job = job;
    }
    intro() {
        console.log("My job is " + this.job);
    }
}

class Coder extends Phh {}

var p = new Person("Leo", 32);
p.greet();
var v = new Coder("Momo", 23, "Coding");
v.greet();
v.intro();

简化:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log('My name is ' + this.name);
    }
}

class Phh extends Person {
    constructor(name, age, job) {
        super(name, age);
        this.job = job;
    }
    intro() {
        console.log('My job is ' + this.job);
    }
}

class Coder extends Phh {
    constructor(name, age) {
        super(name, age, 'Coding');
    }
}

var p = new Person('Leo', 32);
p.greet();
var v = new Coder('Momo', 23);
v.greet();
v.intro();

输出:

My name is Leo
My name is Momo
My job is Coding

这篇关于一个javascript prototype继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆