Skip to content

Instantly share code, notes, and snippets.

@blanklin030
Last active September 5, 2019 08:39
Show Gist options
  • Save blanklin030/1523d15faba808062a7c5b11828f08fe to your computer and use it in GitHub Desktop.
Save blanklin030/1523d15faba808062a7c5b11828f08fe to your computer and use it in GitHub Desktop.
call、Apply、Bind用法
<script>
var obj = {
	"name": "hello"
}
function test(a,b,c) {
	console.log(this.name)
	console.log(a,b,c)
}
test.call(obj,1,2,3)
test.apply(obj,[1,2,3])
test.bind(obj,1,2,3)()
console.log("========myCall===========")
Function.prototype.myCall = function(context, ...args) {
	const fn = Symbol("temp")
	context[fn] = this
	context[fn](...args)
	delete context[fn]
};
test.myCall(obj,4,5,6)
console.log("========myApply===========")
Function.prototype.myApply = function(context,args) {
	const fn = Symbol("temp")
	context[fn] = this
	context[fn](...args)
	delete context[fn]
};
test.myApply(obj, [7,8,9])
console.log("========myBind===========")
Function.prototype.myBind = function (objThis, ...params) {
    const thisFn = this; // 存储源函数以及上方的params(函数参数)
    // 对返回的函数 secondParams 二次传参
    let fToBind = function (...secondParams) {
        const isNew = this instanceof fToBind // this是否是fToBind的实例 也就是返回的fToBind是否通过new调用
        const context = isNew ? this : Object(objThis) // new调用就绑定到this上,否则就绑定到传入的objThis上
        return thisFn.call(context, ...params, ...secondParams); // 用call调用源函数绑定this的指向并传递参数,返回执行结果
    };
    fToBind.prototype = Object.create(thisFn.prototype); // 复制源函数的prototype给fToBind
    return fToBind; // 返回拷贝的函数
};
test.myBind(obj, 10,11,12)()
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment