javascript - Jquery 事件和对象?

标签 javascript jquery oop jquery-events

我正在尝试这样做:

var foo = new Foo();
foo.setEvents( foo );

foo的代码:

function Foo()
{
   this.id = getId(); //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      alert(this.id);
   }
}

每当我运行此代码并单击按钮时,我都会收到一条警告,提示“未定义”

如何在事件触发时保留要运行其方法的对象的状态?

最佳答案

这指的是 jQuery 范围内的不同内容...

function Foo()
{
   obj=this;
   this.id = 1; //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      console.log(obj)
   }
}
var foo = new Foo();
foo.setEvents( foo );

关于javascript - Jquery 事件和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462334/

相关文章:

javascript - React-native:未定义不是一个对象

javascript - 使用jquery点击下拉菜单

javascript - 本地存储: Get specific localstorage value of which contains many items

ruby-on-rails - Rails 为什么要使用委托(delegate)?

javascript - 替换javascript中的类值

javascript - HTML 幻灯片代码

javascript - 使用 jQuery 制作 Nivo slider 方向导航箭头淡入

javascript - 任何人都知道如何从 <Li> Javascript HTML 中自动选择一个选项

Java 接口(interface)和对象

android - 如何在不违反核心 OO 原则的情况下使用 Fragments?