zoukankan      html  css  js  c++  java
  • OOP中this指向详解

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

    this指向的规律(浩哥五条黄金定律!!!
    this指向的情况,取决于函数调用的方式有哪些:

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

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

    //狭义对象
    var obj = {};
    obj.func1 = func;
    obj.func1();//this指向obj
    //广义对象
    document.getElementById("111").onclick = func;//this指向div

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

     ④ 作为window内置函数的回调函数调用 ---> this指向window
    setTimeout(func,1000);//this指向window

     ⑤ 函数作为构造函数,用new关键字调用 ---> this指向新new出的对象
    var obg = new func();//this指向new出的新obg

  • 相关阅读:
    Spring MVC(一)
    Spring-IOC总结
    IT
    Spring基础
    Maven
    Ajax笔记
    数据库和SQL语言
    JDBC
    拦截器
    文件上传
  • 原文地址:https://www.cnblogs.com/wk1102/p/6852581.html
Copyright © 2011-2022 走看看