zoukankan      html  css  js  c++  java
  • JS中的this指向问题

      关于this的指向,是一个令人很头疼的问题。这里我总结了几点,看懂这几点,this指向基本也就没问题了。

      归根结底,this指向就一句话:谁最终调用函数,this指向谁!!!

     关于这点,记住这三句:

           ① this指向的,永远只可能是对象!
           ② this指向谁,永远不取决于this写在哪!而是取决于函数在哪调用。
           ③ this指向的对象,我们称之为函数的上下文context,也叫函数的调用者。


      下面,请看具体情况。

      ① 通过函数名()直接调用:this指向window

     

    function func(){
                console.log(this);
            }
            
    
            //① 通过函数名()直接调用:this指向window
            func(); // this--->window
            

     

    ② 通过对象.函数名()调用的:this指向这个对象

    function func(){
                console.log(this);
            }
    
    //② 通过对象.函数名()调用的:this指向这个对象
                // 狭义对象
                var obj = {
                    name:"obj",
                    func1 :func
                };
                obj.func1(); // this--->obj
                
                // 广义对象
                document.getElementById("div").onclick = function(){
                    this.style.backgroundColor = "red";
                }; // this--->div

    ③ 函数作为数组的一个元素,通过数组下标调用的:this指向这个数组

    function func(){
                console.log(this);
            }
            
    //③ 函数作为数组的一个元素,通过数组下标调用的:this指向这个数组
            var arr = [func,1,2,3];
            arr[0]();  // this--->arr

    ④ 函数作为window内置函数的回调函数调用:this指向window( setInterval setTimeout 等

    function func(){
                console.log(this);
            }
            
    
    //④ 函数作为window内置函数的回调函数调用:this指向window
            setTimeout(func,1000);// this--->window
            //setInterval(func,1000);

    ⑤ 函数作为构造函数,用new关键字调用时:this指向新new出的对象

    function func(){
                console.log(this);
            }
    
    //⑤ 函数作为构造函数,用new关键字调用时:this指向新new出的对象
            var obj = new func(); //this--->new出的新obj

     

     

     

  • 相关阅读:
    Python 列表元素排重uniq
    Python正则表达式汇总
    Python 正则表达式:只要整数和小数
    c++写入txt文件
    OpenMP求完数
    Python分割list
    用ConfigParser模块读写配置文件——Python
    Python 正则表达式
    教程和工具--用wxPython编写GUI程序的
    matlab 之字体调整
  • 原文地址:https://www.cnblogs.com/Xuedz/p/6853706.html
Copyright © 2011-2022 走看看