【发布时间】:2017-01-21 06:08:46
【问题描述】:
如何让原型模式的私有函数成为事件的接收者?到目前为止,我只能使用公共函数作为中介来做到这一点。有没有更直接的方法来做到这一点?
https://plnkr.co/edit/9viJKqdczvfBqgxWG1qW?p=preview
var Person = (function() {
function Person(name) {
console.log('listening...', $('body')[0])
this.name = name;
$('body').on('test', this.onTest.bind(this));
}
Person.prototype.onTest = function(evt) {
_talk.call(this, evt);
}
function _talk(evt) {
console.log(this.name + ' says: ' + evt.payload)
}
return Person;
}());
$(function() {
var p = new Person('Bob');
$('body').trigger({
type: 'test',
payload: 'hello'
});
})
--- 编辑 ---
好的,所以我现在看到我可以做到这一点:
$('body').on('test', function(evt) {
_talk.call(this, evt);
}.bind(this));
...但还是觉得笨拙
【问题讨论】:
-
你不能真的这样做。有点。一个函数要么从外部可见,要么不可见。您可以将其“公开”并坚持使用,也可以尝试有条件地公开。不知何故。归结为本质上具有某种
if (inTest)并随后公开该功能。我想你可以用代理做一些时髦的事情,但我觉得这会增加更多的复杂性和风险,而不是值得。我个人只是公开该功能,但其他人可能不同意。
标签: javascript binding this