javascript this指向和修改指向的方法
来源:Loong Panda
一、不同环境下的this的指向:
1、this的指向是在函数运行时确定下来的,而不是创建的时候,谁调用就指向谁。
2、ES5中普通函数this指向window,ES6中普通函数this指向为undefined;
3、事件的this指向,为事件源本身
4、定时器的this指向,为window.
5、构造函数内部的this指向new出来的这个对象
注: 严格模式下,普通函数和全局环境的this为undefined
1.1 普通函数和全局环境下this
consolog.log(this) // window
function test() { console.log(111, this) // window } test()
注: 'use strict' 严格模式下
consolog.log(this) // undefined
function test() { console.log(111, this) // undefined } test()
1.2对象中的this
let obj3 = {
say() {
console.log(6666, this) // obj3
return function () {
console.log(7777, this) // window
}
}
}
obj3.say()()
1.3构造函数内的this
function Person(e) {
this.name = e console.log(5555, this)
}
let a = new Person('李四1') // Person { name: '李四1'}
let b = new Person('李四2') // Person { name: '李四2'}
1.4定时器下的this
let obj2 = {
name: '张三',
say: function () {
console.log(333, this) // obj2
setTimeout(function () {
console.log(444, this) // window
}, 1000)
}
}
obj2.say()
1.5箭头函数中的this
let obj3 = {
say() {
console.log(6666, this) // obj3
return () => {
console.log(7777, this) // obj3
}
}
}
obj3.say()()
二、改变this指向的方法:
1、箭头函数 -----> 只适合现代浏览器;
2、bind() -----> 第一个是参数是指向谁,第二个以后的参数是自定义的参数,需要单独调用才执行,如: bind(obj)()
3、call(xx, arg1, arg2) -----> 第一个是参数是指向谁,第二个以后的参数是自定义的参数
4、apply(xx, [arg1, arg2]) -----> 第一个是参数是指向谁,第二个的参数是自定义的参数,数据类型必须是数组
例子
function test(arg1, arg2) {
console.log(111, `都${this.age}了,${arg1}${arg2}`)
}
let obj = {
age: 18
}
test('该闭眼睛了!', '不然就没地方埋了') // 都undefined了,该上坟了!
test.call(obj, '该嫁人了!', '不然以后你儿子坐公交车就只能和老奶奶聊天了') // 都18了,该嫁人了!不然以后你儿子坐公交车就只能和老奶奶聊天了
test.apply(obj, ['该离婚了!', '不然其他光棍怎么会有对象呢']) // 都18了,该离婚了!不然其他光棍怎么会有对象呢
test.bind(obj, '该退休了!', '不然钱没花完,人先走了')() // 都18了,该嫁人了!不然以后你儿子坐公交车就只能和老奶奶聊天了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~