【问题标题】:How to create a javascript functional 'class' so that I can access a 'method' from outside and inside the function如何创建一个 javascript 函数“类”,以便我可以从函数外部和内部访问“方法”
【发布时间】:2019-09-09 11:36:27
【问题描述】:

我正在创建一个函数来处理围绕分页和排序表格的一堆东西。它包含一个提交db查询和更新显示表的关键函数。

我希望能够从函数内部以及创建的对象的外部访问该内部函数/方法。

testFunction = function() {
    keyMethod = function() {
        console.log('ya got me');
    };

    document.getElementById('test').addEventListener('click', function (e) {
        keyMethod();
    });

    keyMethod();
};

myTest = new testFunction();
myTest.keyMethod();


testFunction = function() {
    this.keyMethod = function() {
        console.log('ya got me');
    };

    document.getElementById('test').addEventListener('click', function (e) {
        // would have to use bind here which then messes up trying to
        // find the correct target etc.
        keyMethod();
    });

    this.keyMethod();
};

myTest= new DrawShape();
myTest.keyMethod();

以第一种方式创建它意味着 keyMethod 函数在 testFunction 中的任何地方都可用,但我不能从外部调用它。

以第二种方式创建它意味着我可以执行 myTest.keyMethod 但我不能从内部函数中调用它而不使用到处绑定。

有没有更好的方法..?

【问题讨论】:

  • 这几乎是仅有的两个选项。您可能想详细说明目标绑定问题,我们或许可以为您提供一些建议。
  • target-bind 问题,假设我将事件添加到其中包含一些 txt/image/icon 的 a 标签。通常我会做类似 this.getAttribute('blah') 的事情来从 a 标签中获取一些东西。如果我将它绑定到事件函数,我不能这样做,并且 e.target 将指向 a 标签的内容,即他们点击并冒泡到 a 标签的内容。

标签: javascript oop methods


【解决方案1】:

您可以将作为回调提供的函数替换为 arrow function 或使用 bind 函数,就像您已经说过的那样。

testFunction = function() {
    this.keyMethod = function() {
        console.log('ya got me');
    };

    // Replace callback by simply providing the function to call.
    // This works as long as you don't use the `this` keyword inside the
    // provided function.
    document.getElementById('test').addEventListener('click', this.keyMethod);

    // If your callback method does use the `this` keyword you can either use an
    // arrow function or bind the function up front.
    document.getElementById('test').addEventListener('click', event => this.keyMethod());
    document.getElementById('test').addEventListener('click', this.keyMethod.bind(this));

    this.keyMethod();
};

console.log("constructor output:");
myTest = new testFunction();
console.log(".keyMethod() output:");
myTest.keyMethod();
console.log("click event output:");
<button id="test">test</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    相关资源
    最近更新 更多