柯里化函数

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
	<!-- IMPORT CSS -->
	<style>
		.box {
			width: 100px;
			height: 100px;
			background: lightcoral;
		}
	</style>
</head>

<body>
	<div class="box" id="box">珠穆朗玛峰</div>
	<!-- IMPORT JS -->
	<script>
		/* ~ function (proto) {
			function bind(context = window, ...outerArgs) {
				//=>this:要处理的函数
				let _this = this;
				return function proxy(...innerArgs) {
					let args = outerArgs.concat(innerArgs);
					_this.call(context, ...args);
				};
			}
			proto.bind = bind;
		}(Function.prototype); */

		/* ~ function (proto) {
			function bind(context) {
				context = context || window;
				var _this = this;
				var outerArgs = Array.prototype.slice.call(arguments, 1);
				return function proxy() {
					var innerArgs = [].slice.call(arguments, 0);
					let args = outerArgs.concat(innerArgs);
					_this.apply(context, args);
				};
			}
			proto.bind = bind;
		}(Function.prototype);
 */

		let obj = {
			x: 100
		};

		function fn(y, ev) {
			this.x += y;
			console.log(this);
		}

		box.onclick = fn.bind(obj, 200);
		/* 	box.onclick = function proxy(ev) {
			fn.call(obj, ...[200, ev]);
		};*/

		/*
		 * 柯理化函数的思想:
		 *   利用闭包的机制,把一些内容事先存储和处理了,等到后期需要的时候拿来即用即可
		 */
		/*
		 * bind:预先处理内容
		 *   @params
		 * 		func:要执行的函数
		 *      context:需要改变的this指向
		 *      args:给函数传递的参数
		 *   @return
		 * 	    返回一个代理函数
		 */
		/* function bind(func, context, ...args) {
			//=>func:fn
			//=>context:obj
			//=>args:[200,300]
			return function proxy() {
				func.call(context, ...args);
			};
		}
		setTimeout(bind(fn, obj, 200, 300), 1000);
		//=>setTimeout(function proxy(){
		//   func.call(context, ...args);
		//   =>fn.call(obj,200,300);
		//},1000);

		box.onclick = function () {
			//=>点击执行匿名函数,在匿名函数执行的时候再把fn执行
			fn.call(obj, 200);
		};
 		*/
		//=>触发盒子点击事件的时候,把fn执行,并且让fn中的this指向obj,再给fn传递一个200
		// box.onclick = fn; //=>this:box y:MouseEvent

		//=>call/apply都会把函数立即执行,而bind不会立即执行函数,预先存储一些内容(bind不兼容IE8及以下)
		// box.onclick = fn.bind(obj, 200);
	</script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值