首页 > 解决方案 > Object.assign 重新绑定函数

问题描述

因为我需要声誉并且实际上无法对此线程发表评论:Object.assign 方法不绑定“this” 我打开我自己的问题:

这可以以某种方式解决或变通吗?我有一个“主”对象,其中包含

function init(){ console.log(this) }.bind(this)

我正在将此主对象克隆到其他对象中,并且我希望 init 函数在从属对象的范围内运行,而不是在主对象的范围内运行。有什么选择吗?

标签: javascriptjavascript-objects

解决方案


实际上解决了我的问题,这要归功于:

https://gist.github.com/cowboy/5373000

如果 URL 关闭,这里是附加代码:

Function.prototype.bind = (function(origBind) {
  return function() {
    var fn = origBind.apply(this, arguments);
    fn.__origFn__ = this.__origFn__ || this;
    return fn;
  };
}(Function.prototype.bind));

Function.prototype.unbind = function() {
  return this.__origFn__;
};

推荐阅读