简体   繁体   English

从自我对象javascript内部调用的公共方法?

[英]public method called from inside self object javascript?

is there a way to call public method from jquery button click configured inside the same object?? 有没有一种方法可以通过在同一对象内配置的jquery按钮单击来调用公共方法? below I show you the multiple way I have been tried 下面我向您展示了我尝试过的多种方法

var myClass = new MyClass();

function MyClass() {
   this.func1 = function () {
      alert("Hello World");
   }

   var me = this;    
   $("#my-button").click(function(){
      //func1(); //dont work (wold like)
      //this.func1(); //dont work (would like)
      me.func1();   //Work! but is not correct way to do it
      myClass.func1(); //Work! but the idea its that recognize itself widthout call public   instance
  });
}

Other way to do?? 其他方式吗?

me.func1()实际上是正确的方法,尽管我相信惯例是将其命名为“ self”而不是“ me”。

Try this out: 试试看:

var myClass = new MyClass();

function MyClass() {
   var myFunc = function () {
      alert("Hello World");
   }
   this.func1 = myFunc;

   $("#my-button").click(function(){
      myFunc();  
  });
}

Since this inside the click handler refers to my-button , this.func1() won't work. 由于点击处理程序中的this引用了my-button ,因此this.func1()无法正常工作。 func1() won't work because when the click handler is eventually triggered it will be in a different context and func1() doesn't make any sense in that context. func1()无法正常工作,因为最终触发单击处理程序时,它将处于不同的上下文中,而func1()在该上下文中没有任何意义。 Your solution is good. 您的解决方案很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM