zoukankan      html  css  js  c++  java
  • js中this揭秘

    前端面试题中经常会考this指向问题,初学者通常都会晕头转向,不知所以然。今天我就来讲讲js中this指向问题。

    this指向大概分为5种情况,记住这6个规律,基本上面试题都能解决。

    通过圆括号直接调用(this指向window)

    1 var name = "Tom";
    2 
    3 function Person() {
    4     var name = "Jim";
    5     console.log(this.name);
    6 }
    7 
    8 Person();

     作为对象的方法打点调用(this指向调用该方法的对象)

     1 var name = "Tom";
     2 
     3 function Person(name) {
     4     this.name=name;
     5     console.log(this.name);
     6 }
     7 
     8 var p = new Person("Jim");
     9 console.log(this.name);
    10 console.log(p.name);

    作为事件处理调用(this指向发生事件的元素)

    1 var oDiv=document.querySelector("div");
    2 
    3 oDiv.onclick=function(){
    4     console.log(this)
    5 }

    定时器调用(this指向window)

    1 var oDiv = document.querySelector("div");
    2 
    3 oDiv.onclick = function() {
    4     setTimeout(function() {
    5         console.log(this);
    6     }, 1000);
    7 }

    数组下标调用(this指向数组)

    1 var arr = [
    2     "tom",
    3     function() {
    4         console.log(this);
    5     }
    6 ]
    7 
    8 console.log(arr);

    最后一点很重要,记住:this指向取决于函数的最终调用者,函数未被调用时,this指向一般都是window,所以一定要看准函数的调用者,此时可以确定上下文this的指向。

    前端发展速度之快,只有不断的学习积累,才能紧跟时代的步伐。
  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/zt123123/p/7596561.html
Copyright © 2011-2022 走看看