this不同指向
普通function函数中严谨的时候还undefined,不严谨的时候是wind
下列三种除了没有参数是undefined null 是window,有参数传时,传什么,this是什么
- fun.apply
- fun.bind
- fun.call
定时器中的this
定时器箭头函数
let obj = {
name:'666',
fun() {
setTimeout(() => {
console.log(this)
}, 100)
}
}
obj.fun() 是上一层的this
定时器function函数,
let obj = {
name:'666',
fun() {
setTimeout(function(){
console.log(this)
}, 100)
}
}
obj.fun() 是window
手写instanceof
可以判断继承关系,只要是在同一条原型链上,就可以返回true
手写bind
function fun(num1,num2,num3){
console.log(this)
console.log(num1,num2,num3)
return 'hello bind'
}
// let rs = fun.bind({x:'miaomioa'},1,2,3)
// rs()
// 手写bind,arguments是一个伪数组(假数组)
Function.prototype.myBind = function(){
console.log(this)
const arg = Array.prototype.slice.call(arguments);
const _this = arg.shift();
return function(){
fun.apply(_this,arg)
}
}
let rs = fun.myBind({x:'miaomioa'},1,2,3)
rs()