【发布时间】: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