如何在JavaScript中调用当前对象公共方法?
就在那时,我走了这么远如何在JavaScript中调用当前对象公共方法?,javascript,oop,Javascript,Oop,就在那时,我走了这么远 function Class() { var privateMethod = function () { return 'private' } this.publicMethod = function () { return 'public' } var _constructor = function () { $(document).on('click', _onClick)
function Class() {
var privateMethod = function () {
return 'private'
}
this.publicMethod = function () {
return 'public'
}
var _constructor = function () {
$(document).on('click', _onClick)
}
var _onClick = function () {
// My error is `this`, focus now on the click event, but I need the object itself
console.log(privateMethod())
console.log(this.publicMethod())
}
_constructor()
}
$(document).ready(init)
function init() {
new Class()
}
问题是,在click事件中,我无法调用publicMethod。
我可以调用私有方法
如何实现这一点?问题是,在处理程序中,您已经失去了上下文(
此
不再指类的实例,而是指触发事件的对象。您需要创建此
的闭包范围版本以保留该上下文
var self = this;
var _onClick = function () {
// My error is `this`, focus now on the click event, but I need the object itself
console.log(privateMethod())
console.log(self.publicMethod())
}
您有一个范围问题,
onclick中的此
指向的对象与您期望的对象不同。在您的情况下,它是文档
var that = this;
var _onClick = function () {
// My error is `this`, focus now on the click event, but I need the object itself
console.log(privateMethod())
console.log(that.publicMethod())
}
也许你应该尝试javascript模块模式。这看起来有点混乱。但我会尝试一下,谢谢!也谢谢,但我只能接受一个答案,你们都是对的:)