记录高级js学习(四)改变this绑定的方法

60 阅读1分钟

改变this指向的方法(显式绑定)

foo.call(this,a,b,c) 调用函数且传入新的this 与 参数a,b,c

foo.apply(this,[a,b,c]) 调用函数且传入新的this 与 参数a,b,c 区别就是传参需要放在个数组内(两者共同点是都会直接调用函数)

var bar = foo.bind(this,a,b) 返回一个新的函数,且重新绑定个this, 调用bar(c) 则接受的参数顺序为a,b,c,字符串会自动转化为字符串对象(bind后不会调用函数)

function foo(a,b,c){
   console.log(this);     //String{"你好"}
   console.log('a: ', a); //1
   console.log('b: ', b); //2
   console.log('c: ', c); //3
}
var bar = foo.bind("你好",1,2)
bar(3)

new构建一个空的对象被this指向

function foo(a,b){ 
    this.a = a 
    this.b = b 
} 
var bar = new foo(1,2) 
console.log(bar.a) // 1 
console.log(bar.b) // 2