<!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>
function getInfo(age,vip) {
console.log('this',this);
return {
name:this.name,
age:age,
type:vip
}
}
var tina = {
name: 'tina'
}
// 不推荐
// tina.__proto__.getInfo = getInfo
// tina.getInfo = getInfo
// console.log('getInfo.bind()',getInfo.bind(tina,18,"vip"));
// bind()
// 1.任何函数都可以调用
// 2.他有n个参数,至少一个
// 3.返回一个函数并且只有调用该返回函数的时候才可以拿到getInfo返回值
// 4.返回的函数可以作为构造函数使用的时候getInfo的this就失效了
// 手写bind()
var newBind = function(obj){
// 可能只拿到一部分参数
var _this = this
var arr=Array.prototype.slice.call(arguments,1)
var newFun = function(){
// 也可能拿到一部分参数
var arr2 = Array.prototype.slice.call(arguments)
// 调用时拿到当前函数getInfo的返回值
// 合并arr arr2
var list = arr.concat(arr2)
if(this instanceof newFun){
return _this.apply(this,list)
}else{
return _this.apply(obj,list)
}
}
return newFun
}
Function.prototype.newBind = newBind
var tinaFun = getInfo.newBind(tina,18)
console.log('tinaFun',tinaFun("vip"));
</script>
</body>
</html>
手写JavaScript中的bind()方法
于 2022-07-04 23:50:46 首次发布