二十七、this()方法

二十七 this()方法

27.1 this表示触发事件的对象

each()方法的参数是一个函数,函数中的this表示遍历到的该对象。

普通函数中也有this,如果当前函数自执行,this指向window。

举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 添加点击事件
$("#btn").click(function(){
    console.log(this);  // <button id="btn">点我执行代码</button>
});

// 定义一个函数
function fn(){
    console.log(this);  // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
}
// 执行函数
fn();

// 定义一个对象
var obj = {
    a : fn
}
// 现在fn中的this指向obj
obj.a();  // {a: ƒ}

UV4VmV.png

27.2 改变函数的this指向,可以使用call()方法

使用方式:

fn.call() 接受的参数就是要改变的this指向。(可以接收多个参数)

举例:

1
2
3
4
5
6
7
8
9
10
// 定义一个函数
function fun(){
    console.log(this);  
}

// 使用call()方法改变函数中的this指向
// 做了2件事,执行函数 改变this指向 
fun.call($("#btn"));  
fun.call(document)
fun.call(document.body);

UZNnyR.png

点击查看

本文标题:二十七、this()方法

文章作者:Mango

发布时间:2020年07月08日 - 22:29:22

最后更新:2020年07月08日 - 22:35:39

原始链接:https://mango185.github.io/post/a8575354.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------