闭包管理器

来源:互联网 发布:电极式暖手宝 知乎 编辑:程序博客网 时间:2024/05/22 15:00
<script>var Modules = (function Manager(){    var modules = {};    function define(name,deps,impl){        for (var i = 0 ;i < deps.length;i++){            deps[i] = modules[deps[i]];        }        modules[name] = impl.apply(impl,deps);    }    function get(name)    {        return modules[name];    }    return {        define:define,        get:get    }})();Modules.define("bar",[],function(){    function hello(who)    {        return "welcome"+who;    }    return {        hello:hello    }})Modules.define("foo",["bar"],function(bar){    var nameWho = "Kitty";    function awesome()    {        console.log(bar.hello(nameWho).toUpperCase());    }    return {        awesome:awesome    }})var bar = Modules.get("bar");var foo =Modules.get("foo");console.log(    bar.hello("Kitty")    );foo.awesome();</script>

apply:劫持另外一个对象的方法,继承另外一个对象的属性。
Function.apply(obj,args)能接受两个参数
obj:这个对象代替Function类里的this对象
args:这是个数组,它将作为参数传递给Function(args-arguments)

<script>    function hello()    {        {            console.log("hello");        }    }    function hi()    {        hello.apply(this,arguments);        console.log("hi");    }    var Hi = new hi();    //hi.apply("hello",[]);</script>
原创粉丝点击