为什么以下 backbone 查看代码中出现未定义错误?

why undefined error in the following backbone view codes?

const _ = require('underscore');

module.exports = (() => {
  const PANEL_HEADER_HEIGHT = 40;

  return Frame.extend({

  ...
    _handleSearch: _.debounce(ev => {
      if ( ev.keyCode !== 9 ) {
        const searchValue = $(ev.target).val();
        this.model.filterData(searchValue);
      }
    }, 1000),
   ...
})();

this.model.filterData(searchValue); converted to undefined.model.filterData(searchValue); in console.

有什么想法吗?

如果你不使用箭头函数重写方法似乎可行。

https://jsfiddle.net/CoryDanielson/2dt30fhb/

var MyView = Backbone.View.extend({
    name: 'MY-VIEW',
    doStuff: _.debounce(function() {
        alert(this.name);
    }, 1000)
});

var view = new MyView();
view.doStuff();
// This will alert 'MY-VIEW'

它失败的原因是因为 Babel 将转换代码以遵循 ES6 规范。

module.exports = (() => {
  // this = undefined, because module.exports is global.
  return Frame.extend({
    // inherits this from above, undefined
    _handleArrowFunction: _.debounce(ev => {
      console.log(this);
    }),
    _handleRegularFunction: _.debounce(function() {
      console.log(this);
    })
  });
})

看看babel转译代码的区别:

您可以在此处阅读有关箭头函数和 this 值的更多信息: