对象方法中函数的上下文

context in function in object method

有一段代码:

var object = {
    findById: function(idNumber) {
        var data = this.childNodes;
        var returnItems = {};

        function callback(node) {
            if (parseInt(node.id) === idNumber)
                returnItems = node;
        };

        function iterator(node, callback) {
            callback(node);
            var nodes = node.childNodes;
            if (nodes === undefined) {
                return;
            };
            for (var i = 0; i < nodes.length; i++) {
                var iterNode = nodes[i];
                iterator(iterNode, callback);
            };
        };

        function bind(func, context) {
            return function() { // (*)
                return func.apply(context, arguments);
            };
        };

        for (var i = data.length - 1; i >= 0; i--) {
            iterator(data[i], callback);
        };

        return returnItems;
    },
}

如何将上下文导入迭代器和回调函数? 如果我将 console.log(this) 放入函数 iterator() - 这将是 'window',但不是我的对象。 也不应该是 this.callback this.iterator 等。 据我了解,它应该像 call/apply 或绑定。 怎么做到的?

无论你在哪里使用函数,都这样做:

functionToCall.apply(this,params); //this or the context you want to have inside

样本:

function callable() {
   console.log(this);
}
callable(); //logs window
callable.apply({}); //logs {}
  1. findById 函数中复制对此的引用。

    var object = {
      findById: function(idNumber) {
        var data = this.childNodes;
        var returnItems = {};
    
        // assign this to a variable
        // you can use inside the nested functions
        var that = this;
    
    
        function callback(node) {
          if (parseInt(node.id) === idNumber)
            returnItems = node;
        };
    
        function iterator(node, callback) {
          callback(node);
          var nodes = node.childNodes;
          if (nodes === undefined) {
            return;
          };
          for (var i = 0; i < nodes.length; i++) {
            var iterNode = nodes[i];
            iterator(iterNode, callback);
          };
        };
    
        function bind(func, context) {
          return function() { // (*)
            return func.apply(context, arguments);
          };
        };
    
    
        for (var i = data.length - 1; i >= 0; i--) {
          iterator(data[i], callback);
        };
    
        return returnItems;
      }
    };
    
  2. 使用call or apply

    for (var i = data.length - 1; i >= 0; i--) {
      iterator.call(this, data[i], callback);
    };