看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

最新文章

  1. BZOJ3879: SvT
  2. Lua系统库
  3. Linux覆盖率一点研究:获取覆盖率数据
  4. AC日记——单词替换 1.7 21
  5. 建筑行业如何用BPM替换OA?
  6. 内容与Tag
  7. 转:昨天去参加adobe AIR发布会
  8. Android四大图片缓存(Imageloader,Picasso,Glide,Fresco)原理、特性对比
  9. hadoop安装问题记录
  10. mytest 截图
  11. Android View的重绘过程之WindowManager的addView方法
  12. mysql5.7通过json类型替代关联表
  13. Latex引用\ref
  14. linux修改文件为可执行文件
  15. Java如何使套接字向单个客户端显示消息?
  16. MySQL常用SQL语句优化
  17. Linux命令学习之路——变更工作目录:cd
  18. 运用visual studio进行简单的单元测试
  19. Daily Scrum 11.7
  20. 模块-os.system的两个模块/random模块/datetime模块/写日志

热门文章

  1. Codevs 3112 二叉树计数
  2. IT兄弟连 JavaWeb教程 JSP动作指令
  3. 基础篇-环境变量 .bash_profile
  4. 考虑实现Comparable接口
  5. JVM图解
  6. [题解](组合数/二位前缀和)luogu_P2822组合数问题
  7. tagName
  8. (AOP)理解
  9. kafka java api消费者
  10. 关于React的赋值与调用方法