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