美文网首页
参与者模式

参与者模式

作者: 0说 | 来源:发表于2018-12-06 21:45 被阅读0次
    <body>
        在特定的作用域中执行指定的函数,并将参数原封不动的传递
            (函数绑定)                 函数柯里化(参数复用)
    
        用处:
            1、事件执行的时候传递一些额外的参数进去
        <input type="text" name="" id="inp">
        <div id="box"></div>
        <script>
            // 函数柯里化
            // 闭包
            let curry = function(fn){
                // 把curry 的参数保存起来
                let arg = [].splice.call(arguments, 1)
                return function(){
                    let allArr = [...arg, ...arguments]
                    
                    fn.apply(null, allArr)
                }
            }
            
            let fn = function(){
                console.log(arguments);
            };
            
            let cFn = curry(fn, 1, 2); // 永久保存起来
            // 这里可以追加参数
            cFn(4, 5); // 这里fn 打印出来1 2 4 5 
            cFn('a', 'b'); // 这里fn 打印出来1 2 a b
    
    
            // 参与者模式
    
            let curry2 = function(fn, context){  // context  上下文
                let arg = [].splice.call(arguments, 2)
    
                return function(){
                    let allArg = [...arg, ...arguments]
                    fn.apply(context, allArg)
                }
            }
    
            let fn2 = function(){
                this.style.height = '200px'
                this.style.width = '200px'
                this.style.backgroundColor = 'red'
                console.log(arguments)
            }
    
            let resFn = curry2(fn2, box, 2, 3, 4)
            resFn(6, 7, 8)
        </script>
    </body>
    

    相关文章

      网友评论

          本文标题:参与者模式

          本文链接:https://www.haomeiwen.com/subject/qlmacqtx.html