栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将变量绑定到回调函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将变量绑定到回调函数

绑定很简单!

db.startDatabaseConnection(function(){  // whatever}, onError.bind(this, var1, var2));

即使该链接有点长,也可以通过单击此很棒的链接来了解有关绑定的更多信息。

这是一个真正的基本演示

// a functionvar something = function (a, b, c) {  console.log(a, b, c);};// a binding of something with 3 defined argsvar b = something.bind(null, 1, 2, 3);// call bb();//=> 1 2 3

在幕后,这基本上是正在发生的事情

// ES6const myBind = (f, context, ...x) =>  (...y) => f.call(context, ...x, ...y);// ES5var myBind = function(fn, context) {  var x = Array.prototype.slice.call(arguments, 2);  return function() {    var y = Array.prototype.slice.call(arguments, 0);     return fn.apply(context, x.concat(y));  };};var b = myBind(console.log, console, 1, 2, 3);b();// => 1 2 3b(4,5,6)// => 1 2 3 4 5 6

上下文?

上下文允许您动态更改

this
功能。注意,您只能绑定用
function
关键字定义的函数的上下文;箭头函数具有
this
无法操纵的词汇。为了完整起见,显示了此内容,但我建议不要使用此类程序。通常最好只使用另一个函数参数,而不要依赖动态函数上下文
this
。支持这样的上下文切换是为了在Javascript中启用面向对象的样式。除非您使用这种样式,否则我认为没有理由注意上下文。

const getCanvas = (id) =>  document.getElementById(id).getContext('2d')const draw = function (canvas, x = 0, y = 0){ canvas.beginPath()  canvas.strokeStyle = this.color  // `this` refers to context!  canvas.rect(x, y, this.width, this.height)  // `this` refers to context!  canvas.stroke()}// create two contextsconst contextA =  { color: 'blue', width: 10, height: 10 }const contextB =  { color: 'green', width: 10, height: 20 }// bind the draw function to each context and the canvasconst drawA =  draw.bind(contextA, getCanvas('main'))const drawB =  draw.bind(contextB, getCanvas('main'))// call the bound drawing functions normally// draw three blue squaresdrawA(0, 0)drawA(20, 0)drawA(40, 0)// and one green rectdrawB(80, 0)<canvas id="main"></canvas>

部分申请

类似于

bind
ing is Partial
Application

在计算机科学中,部分应用程序(或部分函数应用程序)指的是将多个参数固定到一个函数,从而产生另一个arity较小的函数的过程。

在这里,我们可以制作一个非常简单的

partial
帮助程序,以帮助我们完成此任务

const identity = x =>  xconst partial = (f = identity, ...x) =>  (...y) => f (...x, ...y)const foo = (...all) =>  console.log ('array of', all)partial (foo, 1, 2, 3) (4, 5, 6)// 'array of', [ 1, 2, 3, 4, 5, 6 ]

咖喱

固化与绑定或部分应用有关,但不相同

在数学和计算机科学中,柯里化是一种将接受多个自变量(或自变量元组)的函数的评估转换为评估每个具有一个自变量的函数序列的技术。

const identity = x =>  xconst curry = (f = identity, arity = f.length) => x =>{  const next = (xs = []) =>    xs.length >= arity      ? f (...xs)      : x => next ([ ...xs, x ])  return next ([ x ])}const foo = (a, b, c) =>  console.log ('a', a, 'b', b, 'c', c)curry (foo) (1) (2) (3)// 'a' 1 'b' 2 'c' 3curry (foo) ('choo') ('bye') ()// 'a' 'choo' 'b' 'bye' 'c' undefined


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436478.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号