有趣的this以及apply,call,bind方法

看this指向谁,要看执行时而非定义时(箭头函数除外)。函数没有绑定在对象上调用,非'strict'模式下,this指向window,否则为undefined

改变this指向的方法

1. apply,立即执行

调用方法 fun.apply('想让this指向谁'[,arr]);

参数以数组形式传入

举个栗子(非严格模式):

function fun (params1, params2, params3) {    
console.log('this:', this);    console.log('name:', this.name);
console.log(
'入参:', params1, params2, params3); } let obj = { name: 'LQW' } fun(); fun.apply(obj, [1, 2, 3]);
结果:
this: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} name: 入参: undefined undefined undefined
this: {name: "LQW"} name: LQW 入参: 1 2 3

2. call,立即执行

调用方法 fun.call('想让this指向谁'[,param1,param2,param3…]); 

与apply的入参不同,功能一样

举个栗子(非严格模式):

function fun (params1, params2, params3) {
    console.log('this:', this);
    console.log('name:', this.name);
    console.log('入参:', params1, params2, params3);
}
let obj = {
    name: 'LQW'
}
fun();
fun.call(obj, 1, 2, 3);

结果:
this: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
name: 
入参: undefined undefined undefined
this: {name: "LQW"}
name: LQW
入参: 1 2 3

3.bind,返回一个函数,需要再次调用,bind是javascript高版本的方法,使用时需注意浏览器兼容性

调用方法 fun.bind('想让this指向谁'[,param1,param2,param3…]); 

与call入参相同,bind方法是apply和call的升级版

function fun (params1, params2, params3) {
    console.log('this:', this);
    console.log('name:', this.name);
    console.log('入参:', params1, params2, params3);
}
let obj = {
    name: 'LQW'
}
fun();
fun.bind(obj, 1, 2, 3)();

结果:
this: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
name: 
入参: undefined undefined undefined
this: {name: "LQW"}
name: LQW
入参: 1 2 3

 

posted @ 2018-09-06 16:04  刘倩文  阅读(136)  评论(0编辑  收藏  举报