backbonejs函数未定义

时间:2017-11-14 08:53:03

标签: javascript backbone.js

我遇到的函数未定义。

我获取键值对并在forEach上执行函数。

结构

var AppView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html("Hello World");
    this.one();
  },
  one: function() {
    this.two();
  },
  two: function() {
    var object = {
      "labname4": "423",
      "Path": "4",
      "X": "4"
    };
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
      var value = object[objectKey];
      this.three();
    });
  },
  three: function() {
    console.log('three');
  },
});

var appView = new AppView();
console.log("done");

使用:

  • 的jquery / 1.7.2
  • underscore.js / 1.3.3
  • Backbone.js的/ 0.9.2

2 个答案:

答案 0 :(得分:-1)

因为在调用Object.keys(object).map时更改了范围,所以这也会改变,因此您无法使用它来访问原始值。将其别名为允许您仍然可以访问此原始值。你的代码会像这样扯掉。

var AppView = Backbone.View.extend({

  initialize: function(){
    this.render();
  },
  render: function(){
    this.$el.html("Hello World");
    this.one();
  },

  one: function(){
  this.two();
  },
  two: function(){
  var that = this;
  var object = { "labname4": "423",
                "Path": "4",
                "X": "4"};
    console.log('two');

    Object.keys(object).map(function(objectKey, index) {
        var value = object[objectKey];
        that.three();
    });

  },
  three: function(){
    console.log('three');
  },
});
var appView = new AppView();
console.log("done");

编辑1 var = this vs bind

对我来说,似乎.bind肯定有它的位置。例如,当您在变量中有一个函数并且想要将它附加到特定的函数时。

那就是说,在嵌套的匿名函数的情况下我认为使用var that = this;很简单,与使用.bind相比,需要更少的心理会计。例如,假设我们有两个嵌套函数:

function foo() {
  return (function() {
    doSomething((function() {
      return this.name; // what is `this` again?
    }).bind(this));
  }).bind(this);
}

vs

function foo() {
  var that = this;
  return (function() {
    doSomething((function() {
      return that.name; // `that` is easy to know because its defined 
    })
  })
}

当然,因为这是一种风格问题,“心理会计”的问题因人而异。但是对我来说,考虑到Javascript的这个问题,我认为当你有嵌套的回调时,这很容易理解。

答案 1 :(得分:-2)

使用嵌套函数时,这是一个常见的错误:

Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        });

此处this.three()this不再引用您的对象,因为它位于嵌套函数范围内,并且未在其上定义方法three()

有两种可能的解决方案:

a)使用clojure代替嵌套函数。您可以编写相同的代码,如:

Object.keys(object).map((objectKey, index) => { // note the arrow and no 'function' keyword
            var value = object[objectKey];
            this.three();
        });

clojure保持在当前范围内,因此this.three()将起作用,另一方面function定义它自己的范围。

b)如果您希望它在特定范围内执行,您可以绑定function,如下所示:

Object.keys(object).map(function(objectKey, index) {
            var value = object[objectKey];
            this.three();
        }.bind(this)); // note '.bind(this)'

这样function将使用您当前的范围而不是新的范围。 这两种方法都是有效的,由用户选择一种,我个人更喜欢clojures

相关问题