首页 > 其他 > 详细

this指向问题

时间:2020-03-06 22:31:57      阅读:76      评论:0      收藏:0      [点我收藏+]

this对象是在运行时基于函数执行环境绑定的:在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。

  简而言之:哪个对象调用函数,函数里面的this指向哪个对象。

  当然,在通过call()和apply()改变函数执行环境的情况下,this就会指向其他对象。

  另外,匿名函数执行环境具有全局性。

一、普通函数

  1. 全局作用域下,声明和赋值方式,this指向window

function fn() {
    console.log(this); //window 
}
fn();
var fun = function () {
    console.log(this); //window
}
fun();

  2. 对象方式,this指向绑定函数的对象

var obj = {
    name: ‘spike‘,
    fun: function () {
        console.log(this.name); // spike
    }
}
obj.fun();

  3. 事件绑定方式,this指向绑定函数的标签

var btn = document.querySelector(‘button‘);
btn.onclick = function () {
    console.log(this); // button按钮
}

二、定时器

  this指向window

var timer = setInterval(function () {
    console.log(this); //window
}, 1000)

三、箭头函数

  this指向父级元素的this,没有则指向window

  除了让函数的书写变得很简洁,可读性很好外;最大的优点是解决了this执行环境所造成的一些问题。

var obj = {
    name: ‘spike‘,
    fun: () => {
        console.log(this); //window
    }
}
obj.fun();

四、forEach()

  (this指向undefined),新版本浏览器中,则指向window

var arr = [1, 2, 3];
arr.forEach((item) => {
    console.log(this); // window
})

五、构造函数

  this默认指向,通过构造函数生成的实例化对象;

  如果构造函数中,有事件绑定,事件绑定中的this指向的事件源;

function Fun(name, age) {
    this.name = "spike";
    this.age = 18;
}
var fun = new Fun();
console.log(fun.name, fun.age); // spike 18

六、jQuery事件中的this

  普通的事件绑定,this指向的是绑定事件的标签对象

  第二个参数是事件委托,this指向的是触发事件的标签对象,

  例如:div标签中有span标签,给div绑定事件,然后通过事件委托,定义点击对象是span标签时,触发事件

    JavaScript中,this的指向始终是div标签对象

    jQuery中,事件委托的是span标签,this的指向就是span标签

<div>我是div<span>我是span</span></div>
var div = document.querySelector(‘div‘);
div.onclick = function () {
    console.log(this); // div标签
}
$(‘div‘).on(‘click‘, ‘span‘, function () {
    console.log($(this)); // span标签
})

七、改变this的指向

  call():语法:函数.call(this指向 , 原函数的参数1, 原函数的参数2...);call 方法的参数,应该是对象obj,如果参数为空或null,undefind,则默认传参全局对象 

  apply():语法:函数.apple(this指向 , [原函数的参数1, 原函数的参数2...])

var obj = {};
var f = function () {
    return this;
};
console.log(f());  // window
console.log(f.call(obj)) // obj
console.log(f.call(null)) // window
function Father(name, age) {
    this.name = name;
    this.age = age;
}
// 通过.call改变this指向(第一个参数为Father的this指向,此处传入的this是Son,故改变Father的this指向为Son)
function Son(sex) {
    Father.call(this, "张三", "18");
    this.sex = sex;
}
var s = new Son(‘男‘);
console.log(s.name, s.age, s.sex); // 张三 18 男

 

this指向问题

原文:https://www.cnblogs.com/younghxp/p/12431173.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!