EcmaScript:将所有方法导入到局部作用域中

EcmaScript: Import all methods into local scope

本文关键字:局部 作用域 导入 有方法 EcmaScript      更新时间:2023-09-26

是否有一种方法可以将所有方法导入范围而不需要限定符?其他语言(如Elm)允许这样做。

ES6规范允许:

import {map, where} from 'underscore'; //unqualified imports by name only
import * as _ from 'underscore'; //with qualifier

而不是this:

import * from 'underscore';

我想不出一个不破坏全局命名空间的好方法。但是,如果window对象要被销毁,不妨对其他人的对象也这样做。

另一个人,是iframe。我认为这是一个有趣的方法,如果有任何潜在的缺陷,请留下评论,我会尽量解决它们。

基本上会创建一个iframe。它将有一个脚本元素,其内容将是传递的匿名函数。它的作用域将完全是沙盒,除了任何传入的全局变量(如果需要返回值,以及它们的相关setter)。

使用<<p> /strong>
函数
类型:Function({settings})
允许使用本地化环境 <<p> 设置/em>
类型:PlainObject
配置环境的一组键/值对。目前没有错误处理。
  • 自由
    类型:PlainObject
    这个参数应该是在本地化的全局环境中使用的库

  • fn
    类型:功能
    这将是在本地环境下执行的匿名函数。

  • 全球

  • 类型:PlainObject
    如果需要,global参数将允许在本地化环境和外部上下文之间进行通信。使用键值对,键将是本地化环境中可用的名称。该值将被使用(在这种情况下应该使用外部环境的值),该值将是一个setter(在这种情况下,外部环境的值将在函数执行结束时更新)。这是一个松散设计的实现,如果需要,可以适应更多的情况。

jsFiddle Demo

using函数的定义
function using(args){
 var lib = args.lib;
 var callback = args.fn;
 var global = args.global;
 var iframe = document.createElement('iframe');
 document.body.appendChild(iframe);
 iframe.contentWindow.exec = function() {
    for(var fn in lib){
     this[fn] = lib[fn];     
    }
    for(var val in global){
     this[val] = global[val];
    }
    var scr = document.createElement("script");
    scr.innerHTML = "("+callback+")()";
    iframe.contentWindow.document.body.appendChild(scr);
 };
 iframe.contentWindow.exec();
 for(var val in global){
  if(global[val] instanceof Function)
   global[val](iframe.contentWindow[val]);
 }
 iframe.parentNode.removeChild(iframe);
}

演示代码

var stooges;
var list = document.querySelectorAll(".hello");//just a set of 5 divs classed as hello with w,o,r,l,d in them respectively
using({
 lib: _,
 global: {
     "stooges":function(val){ stooges = val; },
     "list":list
 },
 fn: function(){
  function toUpperCase(x){
   return x.toUpperCase();
  }
  function minSize(len){
   return function(str){
    return str.length >= len; 
   }
  }
  stooges = map(filter(["Larry", "Curly", "Moe"], minSize(4)), toUpperCase);
  each(list,function(el){console.log(el.innerHTML);});
 }
});
console.log(stooges);

从我的发现:不,没有当前或计划的方式导入变量到局部作用域