【问题标题】:JavaScript Inheritance Using .call()使用 .call() 的 JavaScript 继承
【发布时间】:2018-06-15 21:21:20
【问题描述】:

我需要一种方法来调用许多已设置某些默认值的 DHTMLX attach*() 函数。这只是一个例子。如果我能弄清楚这个例子,那么我可以将它应用到所有其他例子中。

DHTMLX 有许多与此类似的功能:dhtmlXCellObject.prototype.attachToolbar()、attachTabbar()、attachRibbon() 等...但是对于我应用程序中的每个工具栏,我都希望自动应用某些设置,例如 iconSize和 iconPath。

dhtmlXCellObject.prototype.attachTheBetterToolbar = function (conf) {
    // https://docs.dhtmlx.com/api__dhtmlxlayout_attachtoolbar.html
    // dhtmlXToolbarObject.prototype.attachToolbar.call(this, conf); This throws: Cannot read property 'call' of undefined

    this.attachToolbar.call(this, conf);

    // I want these two settings below on every single toolbar in our app but
    // I only want to have to set them once in here.  Then throughout my
    // entire application, we will only use attachTheBetterToolbar...
    // layout.cells('a').attachTheBetterToolbar()
    // window.attachTheBetterToolbar()
    // accordian.attachTheBetterToolbar()
    // tabbar.tabs('a').attachTheBetterToolbar()
    // etc...

    this.setIconSize(18);
    this.setIconsPath(c3.iconPath);
};

上面的代码不起作用(错误:this.setIconSize is not a function)但我想你会明白我正在尝试什么。我正在阅读各种关于 JavaScript 扩展、应用、调用、继承等的文章......我觉得我已经接近了,但有些东西没有点击。

我认为“.call()”部分会导致继承发生,如下所述:https://stackoverflow.com/a/16058530/3112803(Variation 1 - Mixin -> Inheritance 示例)

【问题讨论】:

  • 你的实例化是什么样子的?
  • var t = dhtmlXLayout.cells('a').attachTheBetterToolbar();
  • 不确定为什么需要使用.call()this.attachToolbar(conf) 应该做同样的事情。
  • 如果您希望被调用方法中的this 与您正在使用其方法的对象不同,您只需要使用.call()
  • 感谢@Barmar,一直在编码弯曲,斗鸡眼。如果您想要信用,请将其添加为答案。现在编辑 OP 以显示我刚刚尝试过的方法。

标签: javascript inheritance dhtmlx


【解决方案1】:

这可以满足我的需要......

dhtmlXCellObject.prototype.attachTheBetterToolbar = function (conf) {
    var tb = this.attachToolbar(conf);

    // this.setIconset("awesome");
    tb.setIconSize(18);
    tb.setIconsPath(c3.iconPath);

    return tb;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多