js 对象方法内部调用问题

代码如下:为什么报错说searchAjax()不是一个方法

clipboard.png

base.searchEvent();
var base = {
     searchEvent: () => {
        $('input[name="searchText"]').on('keydown', (event) => {
            if (event.key == "Enter" || event.keyCode == 13) {
                // 触发search函数
                this.searchAjax();
            }
            // 阻止冒泡
            return false;
        });
        $('.search-content span').on('click', () => {
            this.searchAjax();
            // 阻止冒泡
            return false;
        });
    },
     searchAjax: () => {
        console.log($('#news').val());
    },
}
阅读 5k
6 个回答

因为this是window

我简写了下代码 按我写的去改
        var base = {
             searchEvent:function (){
                 this.searchAjax();
              console.log(1)
            },
             searchAjax:function (){
                console.log(2)
            }
        }
         base.searchEvent();
         // 输出 2 1
`>> 声明顺序 声明必须在调用之前  我最开始的回答也是需要的 var虽然声明提前 值确实未定义的

因为触发 keydown 事件的时候 this 指向的是 Window

var base = {
     searchEvent: () => {
        $('input[name="searchText"]').on('keydown', (event) => {
            if (event.key == "Enter" || event.keyCode == 13) {
                // 触发search函数
                base.searchAjax();
            }
            // 阻止冒泡
            return false;
        });
        $('.search-content span').on('click', () => {
            base.searchAjax();
            // 阻止冒泡
            return false;
        });
    },
     searchAjax: () => {
        console.log($('#news').val());
    },
}
base.searchEvent();

执行作用域不对

这个是 jQuery?

https://api.jquery.com/on/

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

this 不是 jQuery 对象,需要 jQuery 对象需要 $(this)

这个不是闭包了么 this回调函数的作用域

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题