this的相关文章@TOC
this的详解
- this是当前对象的一个引用,用来承接上下文
- this不是固定不变的,随着执行环境的变化而变化
- 在函数体内部,指代当前函数的运行环境
this的指向
- 在全局环境中,this指向window(在nodejs环境中指向global)
console.log(this) // 此处的this指向的是window
- 局部环境
2.1 严格模式下,函数中的this为undefined
2.2 在全局作用域直接调用函数,隐式相当于window调用,所以指向window
2.3 对象函数调用的时候,哪个对象调用就指向哪个对象function fun () { console.log(this) // 这里的this指向window } fun() // 这里相当于window.fun调用
2.4 new一个构造函数的时候,构造函数中的this指向实例对象const obj1 = { a: 1, fun1 () { console.log(this) }, obj2: { fun2 () { console.log(this) } } } obj1.fun1() // 此处的this指向obj1 obj.obj2.fun2() // 此处的this指向obj2
2.5 在html事件中,this指向了接收事件的html元素Function Fn () { this.a = 1 console.log(this) } const obj = new Fn()
2.6 通过显示绑定改变this的指向<button onclick= "this.style.display='none'">点击我通过this获取元素</button>-
call-无数个参数
- 第一个参数改变this指向
- 之后每个参数为调用函数传进来的参数
- 使用时会自动执行call函数
- 普通函数调用,第一个参数非undefined或者null,this指向第一个参数对象
function fn (a, b, c) { console.log(typeof this) console.log(a) console.log(b) console.log(c) } fn.call(document, 1, 2, 3) // document fn.call(0, 1, 2, 3) // Number(0)-类型:对象 fn.call(false, 1, 2, 3) // Boolean(false)-类型:对象 fn.call('11', 1, 2, 3) // String('11')- 普通函数调用,第一个参数为null或者undefined,this指向window
function fn (a, b, c) { console.log(this) console.log(a) console.log(b) console.log(c) } fn.call(undefined, 1, 2, 3) // window 1 2 3 fn.call(null, 1, 2, 3) // window 1 2 3- 箭头函数调用call无效,直接忽略
-
- apply-两个参数
- 参数1,改变this指向
- 参数二,一个数组,为传递的参数
- 使用时会自动执行apply函数
- 除了传参不同其余和call相同
function fn (a, b, c) {
console.log(this)
console.log(a, b, c)
}
fn.apply(document, 1, 2, 3)
- bind-无数个参数
- 参数1,改变this指向
- 参数二及之后,函数传递进来的实参
- 返回值为一个新的函数
- 使用的时候需要手动再次调用一下返回的新函数
- 和call、apply不一样,绑定bind不会自动执行
function fn (a, b, c) {
console.log(this, a, b, c)
}
const newFn = fn.bind(document, 1, 2, 3)
newFn()
本文详细解析了JavaScript中this关键字的概念及应用。介绍了this在不同环境下的指向规则,包括全局环境、函数调用、对象方法调用、构造函数、事件处理程序以及通过call和apply改变this指向的方法。

被折叠的 条评论
为什么被折叠?



