2025年3月23日 星期日 甲辰(龙)年 月廿二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

JS偏函数

时间:03-07来源:作者:点击数:53

偏函数是 JS 函数柯里化运算的一种特定应用场景。简单描述,就是把一个函数的某些参数先固化,也就是设置默认值,返回一个新的函数,在新函数中继续接收剩余参数,这样调用这个新函数会更简单。

示例1

下面是一个类型检测函数,接收两个参数,第 1 个表示类型字符串,第 2 个表示检测的数据。

  • var isType = function (type, obj) { //偏函数
  • return Object.prototype.toString.call(obj) == '[object ' + type + ']';
  • }

该函数包含两个设置参数,使用时比较繁琐。一般常按以下方式进行设计。

  • var isString = function (obj) {
  • return Object.prototype.toString.call(obj) == '[object String]';
  • };
  • var isFunction = function (obj) {
  • return Object.prototype.toString.call(obj) == '[object Function]';
  • };

函数接收的参数单一,检测的功能也单一和明确,这样更便于在表达式运算中有针对性的调用。下面对 isType() 函数进行扁平化设计,代码如下:

  • var isType = function (type) {
  • return function (obj) {
  • return Object.prototype.toString.call(obj) == '[object ' + type + ']';
  • }
  • }

然后根据 JS 偏函数获取不同类型检测函数。

  • var isString = isType("String"); //专一功能检测函数,检测字符串
  • var isFunction = isType("Function"); //专一功能检测函数,检测字符串

应用代码如下:

  • console.log(isString("12")); //true
  • console.log(isFunction(function () {})); //true
  • console.log(isFunction({})); //false

示例2

下面示例设计一个 wrap() 偏函数,该函数的主要功能是产生一个 HTML 包裹函数,即样式标签。

  • function wrap(tag) {
  • var stag = '<' + tag + '>';
  • var etag = '</' + tag.replace(/s.*/, '') + '>';
  • return function(x) {
  • return stag + x + etag;
  • }
  • }
  • var b = wrap('b');
  • document.write(b('粗体字'));
  • var i = wrap('i');
  • document.write(i('斜体字'));
  • var u = wrap('u');
  • document.write(u('下划线字'));
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门