this的指向以及改变指向的方法

导读:本篇文章讲解 this的指向以及改变指向的方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、函数的调用方式决定了 this 的指向不同:

1.普通函数调用,此时 this 指向 window

    function fn() {
       console.log(this);   // window
     }
     fn();  //  window.fn(),此处默认省略window

2.构造函数调用, 此时 this 指向 实例对象

 function Person(age, name) {
         this.age = age;
         this.name = name
         console.log(this)  // 此处 this 分别指向 Person 的实例对象 p1 p2
     }
    var p1 = new Person(18, 'zs')
    var p2 = new Person(18, 'ww')

this的指向以及改变指向的方法

 

3.对象方法调用, 此时 this 指向 该方法所属的对象

 var obj = {
       fn: function () {
         console.log(this); // obj
       }
     }
    obj.fn();

this的指向以及改变指向的方法

4.通过事件绑定的方法, 此时 this 指向 绑定事件的对象

<body>
    <button id="btn">hh</button>
<script>
    var oBtn = document.getElementById("btn");
    oBtn.onclick = function() {
        console.log(this); // btn
    }
</script>
</body>

this的指向以及改变指向的方法

5.定时器函数, 此时 this 指向 window

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

this的指向以及改变指向的方法

 二、更改this指向的三个方法

1.call() 方法

var Person = {
        name:"lixue",
        age:21
    }
    function fn(x,y){
        console.log(x+","+y);
        console.log(this);
    }
    fn("hh",20);

这段代码中函数fn的this指向为window对象,下面我们使用call改变指向

 var Person = {
        name:"lixue",
        age:21
    }
    function fn(x,y){
        console.log(x+","+y);
        console.log(this);//{name: 'lixue', age: 21}指向了person
        console.log(this.name);
        console.log(this.age);
    }
    fn.call(Person,"hh",20);

this的指向以及改变指向的方法

2.apply() 方法

apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表 

3.bind()方法

bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/79851.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!