下面是看视频时候做的一些笔记
var clear=fuction(){
console.log(this.length);
}
var length=50;
var tom={ c:clear,length:100};
tom.c()
这里是方法调用的方式,打印this.length是50 还是100?
相当于this是指向window还是指向tom呢
结果是100 this:tom
上下调用方式有3种,call、aplly、bind
function f1(){
console.log(this);
} call方法的第一个参数决定了函数内部的this的值
call方法的第一个参数:
1 如果是一个对象类型,那么函数内部的this指向该对象
2 如果是undefind、null,那么函数内部的this指向window
3 如果是数字 ——>this:对应的Number构造函数实例
——>1——>new Number(1)
如果是字符串——>this:String构造函数实例
——>"abc"——>new String("abc")
如果是布尔值——>this:boolean构造函数的实例
——>false——> new Boolean(false)
call和apply都可以改变函数内部的this的值
不同的地方:传参的形式不同
function toString(a,b,c){
return a+" "+b+" "+c;
}
toString.call(null,1,3,5)
toString.apply(null,[1,3,5])
bind的基本用法
function speed(){
console.log(this.seconds);
}
执行了bind方法之后,产生了一个新函数,这个新函数里面的逻辑和原来还是一样的,唯一不同的是this指向{ seconds:100}
var speedBind = speed.bind({ seconds:100 })
speedBind();