设置'this'多着呢

Settings the context of 'this' in IIFE

本文关键字:this 设置      更新时间:2023-09-26

我想将以下代码的'this'上下文绑定到Collection原型对象,但现在它指的是窗口对象。

到目前为止,我已经尝试将函数定义包装为IIFE,但这并没有改变上下文。

我的代码
Mongo.Collection.prototype.bulk = (function(){
  var context = this; <------- should refer to the prototype's context and not the object 'bulk'
  return {
    insert: function(documents, options) {
    },
    update: function() {
    },
    upsert: function() {
    }
  };
})();

如何做到这一点?

格雷厄姆的评论是正确的答案。不需要生命。你可以直接输入prototype.fn = function() { var context = this; }

但是如果(不管出于什么原因)你不能那样做……然后你可以传递任何你想使用的context作为IIFE的参数:

Mongo.Collection.prototype.bulk = (function(context){
  return {
    insert: function(documents, options) {
    },
    update: function() {
    },
    upsert: function() {
    }
  };
})(Mongo.Collection.prototype);