我如何使这个窗口时.call(this)从commonJS模块
How do I make this window when .call(this) from a commonJS module
我正在使用Webpack来打包我的依赖,我正在尝试加载方法组合器。依赖项如下所示:
// Generated by CoffeeScript 1.3.1
(function() {
var __slice = [].slice;
this.before = function(decoration) {
return function(base) {
return function() {
decoration.apply(this, arguments);
return base.apply(this, arguments);
};
};
};
...
}).call(this);
然后在我的TS文件中包含…
require("method-combinators/lib/method-combinators.js");
当我在内部函数上断点时,我注意到this != window
。如果我想添加…
require.bind(window);
我得到
Critical dependencies: 20:0-7 require function以某种方式使用哪些依赖项不能静态提取
正确的方法是什么?
> this
Object {}
> window
Window {...}
如果我这样做
window['comb'] = require("method-combinators/lib/method-combinators.js");
似乎可以工作,但是因为这是遗留代码,所以很难搜索after和begin的所有实例。
更新2
var comb = require("method-combinators/lib/method-combinators.js");
window['after'] = comb.after;
window['before'] = comb.before;
这与@tcooc提供的答案类似,但问题是我必须列出每个函数。对于下划线,我有这样的内容…
var s = require("underscore.string");
window['_'].mixin(s.exports());
但是这里的问题是梳子没有exports
更新3
这是我最后的
var comb = require("method-combinators/lib/method-combinators.js");
window['_'].extend(window, comb);
commonjs模块,按照设计,不访问或修改全局作用域(或者至少他们不应该)。代码中的this
变量引用的是从该模块导出的值,而不是window
。代码实际上是这样包装的(针对您的用例进行了简化):
// you want to load "method-combinator.js"
require('method-combinator.js');
// load "method-combinator.js" as "dependency()"
var exports = {};
dependency.call(exports);
现在当你尝试加载"method-combinator.js"时,返回exports
。
使用依赖的正确方法是:
var combinators = require('method-combinator.js');
如果您希望将combinators
的所有值添加到window
,假设您有下划线:
_.extend(window, combinators);
// or if _ is somehow not resolving properly (for some reason?)
window._.extend(window, combinators);
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- 如何捆绑commonjs模块,除非指定需要
- Understanding Javascript scope with "var that = this&qu
- 定义this.properties或objectName.properties的javascript JSON对象
- Object.prototype using 'this'
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Javascript 对象和 this 关键字
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- 定义CommonJS模块时,fn.call(this)与fn()的对比
- 我如何使这个窗口时.call(this)从commonJS模块