JavaScript设计模式(三十二):异国战场-参与者模式

简介: 异国战场-参与者模式

参与者(participator)

在特定的作用域中执行给定的函数,并将参数原封不动地传递

需求:实现系统的bind功能

传递参数

存在的缺点添加的事件回调函数不能移除(removeEventListener)

function $(id) {
   
    return document.getElementById(id);
}

const A = {
   
    on(dom, type, fn, ...args) {
   
        dom.addEventListener(type, function (e) {
   
            fn && fn(dom, e, args);
        }, false);
    }
};

A.on($('btn1'), 'click', function (dom, e, args) {
   
    console.log(dom, e, args); // DOM  PointerEvent{}  [{ name: 'Lee' }, { age: 18 }]
}, {
    name: 'Lee' }, {
    age: 18 });

函数绑定

实现建简易的bind功能

function bind(context, fn) {
   
    return function (...args) {
   
        return fn.apply(context, args);
    }
}

let bindFn = bind({
    name: 'Lee', age: 18 }, function (msg) {
   
    console.log(`${msg} ${this.name}`);
});

bindFn('Hello'); // Hello Lee

bind应用于事件

这种方式传参还是存在一定的局限性,我们必须事先明确参数是什么然后在传递下去(通过柯里化解决此问题

function $(id) {
   
    return document.getElementById(id);
}

function bind(context, fn) {
   
    return function (...args) {
   
        return fn.apply(context, args);
    }
}

const bindFn = bind({
    dom: $('btn1'), args: {
    name: 'Lee' } }, function (e) {
   
    console.log(this, e); // {dom: button#btn1, args: { name: 'Lee' }}  PointerEvent{}
    this.dom.removeEventListener('click', bindFn);
});

$('btn1').addEventListener('click', bindFn, false);

原生bind

function sayHi(name) {
   
    console.log(`${this.msg} ${name}`);
}

let bindFn = sayHi.bind({
    msg: 'Hello' }, 'Lee');

bindFn(); // Hello Lee

函数柯里化

函数柯里化的思想是对函数的参数分割,类似面向语言中的类的多态,根据传递的参数不同,可以让一个函数存在多种状态

实现函数的柯里化是以函数为基础的,借助柯里化器伪造其他函数,让这些伪造的函数在执行时调用这个基函数完成不同的功能

通过函数柯里化器对add方法实现的多态拓展且不需要像以前那样明确声明函数了,因为函数的创建过程已经在函数柯里化器中完成了

// 创建柯里化器
function curry(fn, ...args1) {
   
    return function (...args2) {
   
        // 所有参数
        let args = [...args1, ...args2];
        return fn.apply(null, args);
    }
}

curry((...args) => {
   
    console.log(args); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
}, 1, 2, 3, 4, 5, 6)(7, 8, 9);


// 加法器
function add(a, b) {
   
    return a + b;
}

let sum1 = curry(add, 1)(2);
console.log(sum1); // 3

let sum2 = curry(add, 1, 2)();
console.log(sum2); // 3

利用柯里化重构bind

优化传参

function $(id) {
   
    return document.getElementById(id);
}

function bind(context, fn, ...args1) {
   
    return function (...args2) {
   
        // 所有参数
        let args = [...args1, ...args2];
        return fn.apply(context, args);
    }
}

const bindFn1 = bind(null, (...args) => {
   
    console.log(args); // [1, 2, 3, 4, 5, 6, 7, 8]
}, 1, 2, 3, 4, 5)

bindFn1(6, 7, 8);

const bindFn2 = bind($('btn1'), function (a, b, ...args) {
   
    console.log(this, a, b, args); // DOM  [1, 2, 3, 4, 5, 6, PointerEvent]
    this.removeEventListener('click', bindFn2);
}, 1, 2, 3, 4, 5, 6);

$('btn1').addEventListener('click', bindFn2, false);

兼容bind方法

// 兼容各个浏览器
if (Function.prototype.bind === undefined) {
   
    Function.prototype.bind = function (context, ...args1) {
   
        const that = this;
        return function (...args2) {
   
            // 所有参数
            let args = [...args1, ...args2];
            return that.apply(context, args);
        }
    }
}

const logNum = function (...args) {
   
    console.log(args); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
};

logNum.bind(null, 1, 2, 3, 4, 5)(6, 7, 8, 9);

特点

  • 参与者模式实质上是两种技术的结晶
    1. 函数绑定
    2. 函数柯里化

反柯里化

方便对方法的调用

// 反柯里化
Function.prototype.uncurry = function () {
   
    var that = this;
    return function (...args) {
   
        return Function.prototype.call.apply(that, args);
    }
};

// 以前的方法
{
   
    Object.prototype.toString.call(function () {
    });    // '[object Function]'
    Object.prototype.toString.call([]);                 // '[object Array]'
    Object.prototype.toString.call(123);                // '[object Number]'
}

// 反柯里化后的方法
{
   
    const toString = Object.prototype.toString.uncurry();
    toString(function () {
    });  // '[object Function]'
    toString([]);               // '[object Array]'
    toString(123);              // '[object Number]'
}

var push = [].push.uncurry(); // 保存数组push方法
var obj = {
   };
push(obj, 'Lee', 18); // 通过push方法为对象添加数据成员
console.log(obj); // {0: 'Lee', 1: 18, length: 2}
目录
相关文章
|
1天前
|
存储 前端开发 JavaScript
回调函数是JavaScript中处理异步编程的常见模式,常用于事件驱动和I/O操作。
【6月更文挑战第27天】回调函数是JavaScript中处理异步编程的常见模式,常用于事件驱动和I/O操作。它作为参数传递给其他函数,在特定条件满足或任务完成后被调用。例如,`asyncOperation`函数接受回调函数`handleResult`,模拟异步操作后,调用`handleResult`传递结果。这样,当异步任务完成时,`handleResult`负责处理结果。
10 1
|
2天前
|
设计模式 JavaScript 前端开发
[JavaScript设计模式]惰性单例模式
[JavaScript设计模式]惰性单例模式
|
2天前
|
设计模式 存储 算法
设计模式学习心得之五种创建者模式(2)
设计模式学习心得之五种创建者模式(2)
12 2
|
3天前
|
设计模式 搜索推荐
工厂方法模式-大话设计模式
工厂方法模式-大话设计模式
6 1
|
11天前
|
设计模式 存储 JavaScript
【JavaScript】JavaScript对象设计哲学:八种模式塑造高效代码
【JavaScript】JavaScript对象设计哲学:八种模式塑造高效代码
18 5
|
8天前
|
设计模式 Java 数据库连接
Java设计模式之工厂方法模式详解
Java设计模式之工厂方法模式详解
|
8天前
|
设计模式 算法
行为型设计模式之模板模式
行为型设计模式之模板模式
|
20天前
|
设计模式 新零售 Java
设计模式最佳套路5 —— 愉快地使用工厂方法模式
工厂模式一般配合策略模式一起使用,当系统中有多种产品(策略),且每种产品有多个实例时,此时适合使用工厂模式:每种产品对应的工厂提供该产品不同实例的创建功能,从而避免调用方和产品创建逻辑的耦合,完美符合迪米特法则(最少知道原则)。
35 6
|
20天前
|
设计模式 XML Java
【设计模式】第三篇:一篇搞定工厂模式【简单工厂、工厂方法模式、抽象工厂模式】
三 结尾 如果文章中有什么不足,欢迎大家留言交流,感谢朋友们的支持! 如果能帮到你的话,那就来关注我吧!如果您更喜欢微信文章的阅读方式,可以关注我的公众号
22 5
|
20天前
|
设计模式 Java 关系型数据库
设计模式第2弹:工厂方法模式
type ComputerProduct struct{} // 实现工厂方法 func (computer ComputerProduct) GetInformation() string { return "电脑,官方称呼计算机,主要用于进行数据运算的一台机器。" }
27 4