使用原生ES5封装 call, apply, bind 等方法
Posted ox1dp6ei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用原生ES5封装 call, apply, bind 等方法相关的知识,希望对你有一定的参考价值。
直接上代码,大家一看就明了
<!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>
以上是关于使用原生ES5封装 call, apply, bind 等方法的主要内容,如果未能解决你的问题,请参考以下文章
es6 class的基础语法,es6 class继承/ es5 call继承描述/使用apply比较完美继承Array的方法 sort倒序排序console.table()表格生成
原生实现JavaScript的call()apply()bind()