gpt4 book ai didi

javascript - 如何使用揭示原型(prototype)模式在内部调用覆盖的方法

转载 作者:行者123 更新时间:2023-11-29 19:43:20 25 4
gpt4 key购买 nike

我目前正在为 Javascript 中的 Revealing Prototype Pattern 的一些概念和语法而苦苦挣扎。你们能帮我理解一下吗?

我想要实现的目标是:从基类的另一个方法调用重写的方法。

我是怎么做到的:

  1. 基类:

    var Base = function() {
    //...
    };
    Base.prototype = function() {
    var init = function() {
    console.log('init');
    customInit.call(this);
    },
    customInit = function() {
    console.log('custom init source');
    };

    return {
    init: init,
    customInit: customInit
    };
    } ();
  2. 扩展类:

    var Extended = function () {
    //...
    };
    Extended.prototype = new Base();
    Extended.prototype.customInit = function () {
    console.log('custom init extended');
    };
  3. 调用扩展类:

    window.addEventListener('load', function (){
    var myObject = new Extended();
    myObject.init();
    myObject.customInit();
    });

从类外部调用 customInit 执行方法的覆盖版本(我想要的),而从类内部调用仍然调用方法的“基础”版本(不是我想要的)。

这正常吗?有什么解决方法可以实现这一目标吗?

最佳答案

对您的代码进行一些修改(1 行):

.......
var init = function() {
console.log('init');
//customInit.call(this);
this.customInit.call(this);
},
.....

关于javascript - 如何使用揭示原型(prototype)模式在内部调用覆盖的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21625098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com