Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bind函数的模拟实现 #11

Open
conan1992 opened this issue Jun 8, 2020 · 0 comments
Open

bind函数的模拟实现 #11

conan1992 opened this issue Jun 8, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

bind()

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

当目标函数被调用时,被预置入绑定函数的参数列表中的参数。

模拟实现第一步

Function.prototype.bind2 = function(){
	var thatFun = this;
	var context = arguments[0];
	var args = Array.prototype.slice.call(arguments, 1);

	return function(){
		var newArgs = args.concat( Array.prototype.slice.call(arguments))
		return thatFun.apply(context, newArgs)
	}
}

模拟实现第二步、

当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。

Function.prototype.bind2 = function(){
	var thatFun = this;
	var context = arguments[0];
	var args = Array.prototype.slice.call(arguments, 1);

	var fBound =  function(){
		var newArgs = args.concat( Array.prototype.slice.call(arguments))
		return thatFun.apply(this instanceof fBound ? this : context, newArgs)
	}
	fBound.prototype = this.prototype
	return fBound;
}

模拟实现第三部-优化

	//调用 bind 的不是函数
	if (typeof this !== "function") {
		throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
	}

	var thatFun = this;
	var context = arguments[0];
	var args = Array.prototype.slice.call(arguments, 1);
	var fNOP = function () {}; 
	var fBound =  function(){
		var newArgs = args.concat( Array.prototype.slice.call(arguments))
		return thatFun.apply(this instanceof fBound ? this : context, newArgs)
	}
	fNOP.prototype = this.prototype
	fBound.prototype = new fNOP();
	return fBound;
}

生产使用

if (!Function.prototype.bind) (function(){
	Function.prototype.bind = function(){
		...
	}
})

或者

Function.prototype.bind = Function.prototype.bind || function () {
    ……
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant