在事件处理程序中调用函数

Pra*_*een 2 javascript jquery event-handling javascript-events

我在Javascript代码中编写了2个函数,如下所示

Manager = FormManager.extend({
    First: function () {
     var response = this.Second("Feature"); //I'm able to get the alert

     //I have added a click event handler
     $('#element').on('click', function(){
       var newResponse = this.Second("Bug"); //The alert is not poping
     });

    }

    Second: function (type) {
     alert(type);
     //Performs certain operation
    }
});
Run Code Online (Sandbox Code Playgroud)

错误:未捕获TypeError:对象#没有方法'秒'

我也尝试过不使用this关键字

Second("Bug") // Error: There is no method
Run Code Online (Sandbox Code Playgroud)

虽然这是我正在玩的程序的简化格式(按顺序显示一个简单的例子).我正在努力找出原因.

有人可以指引我走正确的道路吗?

PSL*_*PSL 6

你使用不正确this.试试这种方式.this处理程序内部不代表#element函数本身的上下文.

 var self = this; //cache the context here
 $('#element').on('click', function(){
   var newResponse = self.Second("Bug"); //Access it with self
 });
Run Code Online (Sandbox Code Playgroud)

此外,我认为你在First功能定义之后和Second功能之前缺少一个逗号.

小提琴

您给出的回调的原因是从元素的上下文中调用,以便您的this上下文发生更改.thiscontext指的是调用回调的上下文.但是还有其他方法可以解决这个问题,例如使用$ .proxy,同时使用ecmaScript5 Function.prototype.bind将回调绑定到jquery,但理想情况下你不想这样做,因为大多数情况下你需要上下文处理程序内部的元素.

  • @ user1671639没什么不好的.但是如果你正在寻找更多的对象模型类型声明,你可以看一下EcmaScript5`Object.create`模式.但是当你在像Node.js这样的租户上运行时,这又有帮助,但只有较新的浏览器支持这一点.另外,这些更多是statix方法绑定,因为你不需要它们的实例. (2认同)