为什么这段代码会出现错误 "Hi不是一个函数"

问题描述 投票:-3回答:1

当用户点击.step时,jquery会执行hello函数,工作正常。hello函数将调用hi函数=> 我在这里得到了错误。Hi不是一个函数

jQuery(document).ready(function( $ ) {
    const form = {

        init: function() {
            $('.step').on('click', this.hello)
        },

        hello: function() {
          console.log('Index: ', $(this).index()); // I can get the right index
          this.hi(); // ERROR: Hi is not a function!
        },

        hi: function() {
            console.log('HI')
        },
    }

    form.init()
})

当我输入这样的代码时,它可以正常工作

jQuery(document).ready(function( $ ) {
    const form = {

        init: function() {
            $('.step').on('click', this.hi) // Look here
        },

        hi: function() {
            console.log('HI')
        },
    }

    form.init()
})

你们能解释一下原因吗?

javascript jquery
1个回答
1
投票

嗨不是一个函数

谁能解释一下为什么?

在这段代码中

    init: function() {
        $('.step').on('click', this.hello)
    },

    hello: function() {
      console.log('Index: ', $(this).index()); // I can get the right index
      this.hi(); // ERROR: Hi is not a function!
    },

您设置 form.hello 作为 事件处理程序 的点击事件。 在事件处理程序内。this 是被点击的元素,如。

  $("button").click(function() { console.log(this.id); }

扣子 将(鉴于此代码)没有 .hi 方法。

如何避免使用Es6或箭头函数进行绑定?

如果你不需要知道哪个按钮被点击,你可以在定义事件处理程序时使用箭头函数。

    init: function() { 
        $('.step').on('click', () => this.hello())
    },

例如: https:/jsfiddle.netmcuh5awt2

理想情况下,你会希望同时访问按钮的 表单类,这有两种方式,第一种是改变你定义类的方式,但与你的方式保持一致,我们可以添加一个新的属性。self 来存储对它的......嗯......自我的引用......。

jQuery(document).ready(function( $ ) {
    const form = {
        self : {},

        init: function() {
            self = this;
            $('.step').on('click', self.hello)
        },

        hello: function() {
          console.log('Index: ', $(this).index());
          self.hi(); 
        },

        hi: function() {
            console.log('HI')
        },
    }

    form.init()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button class='step' type='button'>
Step 1
</button>
<button class='step' type='button'>
Step 2
</button>
</div>

由于这将成为你的类的一个公共属性,你可能会喜欢在这种情况下使用不同的名称,如 form 以匹配班级名称。

© www.soinside.com 2019 - 2024. All rights reserved.