如以下代码,User 之中应该包含 VIPUser 但是VIPUser却用不了User的sayHello 方法,

    1. function User(firstName, lastName, age) {
    2. this.firstName = firstName;
    3. this.lastName = lastName;
    4. this.age = age;
    5. this.fullName = this.firstName + " " + this.lastName;
    6. }
    7. User.prototype.sayHello = function() {
    8. console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`);
    9. }
    10. function VIPUser(firstName, lastName, age, money) {
    11. User.call(this, firstName, lastName, age);
    12. this.money = money;
    13. }
    14. VIPUser.prototype.upgrade = function() {
    15. console.log(`使用了${100}元软妹币,升级了!`);
    16. this.money -= 100;
    17. }
    18. var vUser = new VIPUser("姬", "成", 1, 100);
    19. </script>

    它们原型链如下图
    IMG_20200721_144957.jpg
    如何让 vUser也可以是使用 User的方法呢

    1. function User(firstName, lastName, age) {
    2. this.firstName = firstName;
    3. this.lastName = lastName;
    4. this.age = age;
    5. this.fullName = this.firstName + " " + this.lastName;
    6. }
    7. User.prototype.sayHello = function () {
    8. console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`);
    9. }
    10. function VIPUser(firstName, lastName, age, money) {
    11. User.call(this, firstName, lastName, age);
    12. this.money = money;
    13. }
    14. myplugin.inherit(VIPUser , User)
    15. VIPUser.prototype.upgrade = function () {
    16. console.log(`使用了${100}元软妹币,升级了!`);
    17. this.money -= 100;
    18. }
    19. var vUser = new VIPUser("姬", "成", 1, 100);
    20. // 继承 es5的方法 圣杯
    21. if (!this.myplugin) {
    22. this.myplugin = {};
    23. }
    24. this.myplugin.inherit = function (son, father) {
    25. son.prototype = Object.create(father.prototype);//create/es5 创建一个新对象,其隐式原型指向father.prototype
    26. son.prototype.constructor = son;
    27. son.prototype.usber = father.prototype
    28. }

    原型链如下
    IMG_20200721_143447.jpg
    老版本的方法 圣杯

    1. this.myplugin.inherit = function (son, father) {
    2. // 之前的写法 圣杯模式
    3. function Temp() { };
    4. Temp.prototype = father.prototype;
    5. son.prototype = new Temp();
    6. son.prototype.constructor = son;
    7. son.prototype.usber = father.prototype;
    8. // 高级简化版
    9. (function () {
    10. function Temp() { };
    11. return function (son, father) {
    12. Temp.prototype = father.prototype;
    13. son.prototype = new Temp();
    14. son.prototype.constructor = son;
    15. son.prototype.usber = father.prototype
    16. }
    17. })(son, father)
    18. }

    原型链如下
    IMG_20200721_135624.jpg