实现call方法
Function.prototype.lycall = function (thisArg, ...args) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
thisArg.fn = fn;
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function foo() {
console.log(this);
}
foo.lycall(null);
function sum(num1, num2) {
console.log()
console.log("sum==>", num1 + num2);
}
sum.lycall('proxyParam',10, 50);
实现apply
Function.prototype.lyapply = function (thisArg,argArray) {
var fn = this
thisArg = ![null,undefined].includes(thisArg) ? Object(thisArg) : window
var result
thisArg.fn = fn
argArray = argArray || []
result = thisArg.fn(...argArray)
delete thisArg.fn
return result
}
function foo () {
console.log(this)
}
foo.lyapply()
function sum (num1,num2) {
return num1 + num2
}
var count = sum.lyapply('proxyValue',[10,60])
console.log(count)
function bar () {
console.log('执行了bar函数',0)
}
bar.lyapply(0)
实现bind
Function.prototype.lybind = function (thisArg,argArray) {
var fn = this
thisArg = ![null,undefined].includes(thisArg) ? Object(thisArg) : window
function proxyFn (...args) {
thisArg.fn = fn
var finalArray = [...argArray,...args]
var result = thisArg.fn(...finalArray)
delete thisArg.fn
return result
}
return proxyFn()
}
function foo () {
console.log(this)
}
foo.bind()()
function sum (num1,num2) {
return num1 + num2
}
var callback = sum.bind('aaa',20,50)
console.log(callback())
测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./实现bind.js"></script>
</body>
</html>
****