【问题标题】:javascript prototype call method in a "Click" event“点击”事件中的javascript原型调用方法
【发布时间】:2017-07-11 17:46:01
【问题描述】:

我对 javascript 原型有点陌生。我无法在事件处理程序中调用方法,它只是一直说“不是函数”。有人可以帮我指出我做错了什么。我感谢任何 cmets。谢谢。这是我的代码

var oneStepCheckOutEnhance = Class.create();
oneStepCheckOutEnhance.prototype = {
   test: function Test() {       
      alert('test');
   },

   observeShippingMethod: function () {
       $$('dl.shipment-methods input').invoke('observe', 'click', function  () {
          this.test(); //Keep saying Uncaught TypeError: this.test is not a function            
       });
    },    
};

我是这样称呼的:

<script type="text/javascript">
   var onStepEnhance = new oneStepCheckOutEnhance();
   onStepEnhance.observeShippingMethod();
</script>

【问题讨论】:

    标签: javascript methods call


    【解决方案1】:

    this 在您调用它的范围内是它命中的第一个函数闭包(即处理点击的匿名函数),而不是对象。您可以像这样将它绑定到父对象:

    var oneStepCheckOutEnhance = Class.create();
    oneStepCheckOutEnhance.prototype = {
       test: function Test() {       
          alert('test');
       },
    
       observeShippingMethod: function () {
           $$('dl.shipment-methods input').invoke('observe', 'click', function  () {
              this.test();         
           }).bind(this); // right here, it binds the handler to the parent scope.
        },    
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2011-12-01
      • 2016-09-15
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多