共计 1962 个字符,预计需要花费 5 分钟才能阅读完成。
间接上代码,大家一看就明了
<!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>
<h2>call-apply-bind</h2>
<script>
'use strict'
Function.prototype.call = function () { // 纯 es5 写法
var targetFuc = this;
var thisArg = arguments[0]
if (!(typeof thisArg === 'object' || typeof thisArg === 'function') ) {throw new Error( 'type error')
}
thisArg.nestFuc = targetFuc
var evalString = 'thisArg.nestFuc('
for (var i = 1; i < arguments.length; i++) {evalString += 'arguments[' + i + '],'
}
evalString += ')'
console.log(evalString)
return eval(evalString)
}
Function.prototype.apply = function (thisArg, argArray) {if ( !(typeof thisArg === 'object' || typeof thisArg === 'function') ) {throw new Error( 'type error')
}
var targetFuc = this;
thisArg.nestFuc = targetFuc
var evalString = 'thisArg.nestFuc('
for (var i = 0; i < argArray.length; i++) {evalString += 'argArray[' + i + '],'
}
evalString += ')'
console.log(evalString)
return eval(evalString)
}
Function.prototype.bind = function () {
var targetFuc = this;
var slice = Array.prototype.slice
var argumentsArray = slice.call(arguments)
var thisArg = argumentsArray[0]
if (!(typeof thisArg === 'object' || typeof thisArg === 'function') ) {throw new Error( 'type error')
}
return function () {targetFuc.apply( thisArg, argumentsArray.slice(1).concat(slice.call( arguments) ) )
}
}
var f1 = function (x,y) {console.log( this, x, y) }
f1.call({ a: 1}, 6, 7 )
f1.apply({ a: 1}, [6, 7] )
var f2 = function (x,y) {console.log( this, x, y) }
f2.bind({ b:1}, 8, 9 )()
</script>
</body>
</html>
正文完
发表至: javascript
2021-03-23