• 谈谈你对This对象的理解?


    1、this总是指向函数的直接调用者(而非间接调用者);
    2、如果有new关键字,this指向new出来的那个对象;
    3、在事件中,this指向触发这个事件的对象,特殊的是,IE中的attachEvent中的this总是指向全局对象
    Window;
    看看下边几个例子,或许可以更好的理解this对象
    this的指向

    this表示当前对象,this的指向是根据调用的上下文来决定的,默认指向window对象
    全局环境
    全局环境就是在<script></script>里面,这里的this始终指向的是window对象,
    <script>console.log(this)</script> 指向window对象
    局部环境

    在全局作用域下直接调用函数,this指向window
    <script>
    function func(){
    console.log(this) ;//this指向的还是window对象
    }
    func();
    </script>
    对象函数调用,哪个对象调用就指向哪个对象

    <input type="button"id="btnOK" value="OK">
    <script>
    varbtnOK=document.getElementById("btnOK");
    btnOK.onclick=function(){
    console.log(this);//this指向的是btnOK对象
    }
    </script>
    使用 new 实例化对象,在构造函数中的this指向实例化对象。

    <script>
    var Show=function(){
    this.myName="Mr.Cao"; //这里的this指向的是obj对象
    }
    var obj=new Show();
    </script>
    使用call或apply改变this的指向


    <script>
    var Go=function(){
    this.address="深圳";
    }
    var Show=function(){
    console.log(this.address);//输出 深圳
    }
    var go=new Go();
    Show.call(go);//改变Show方法的this指向go对象
    </script>

  • 相关阅读:
    Luogu P1131 时态同步
    Codeforces Round #507 B. Shashlik Cooking
    Codeforces Round #507 A. Palindrome Dance
    Luogu P3818 小A和uim之dark♂逃离 Ⅱ
    Luogu P1373 小a和uim之dark♂逃离 Ⅰ
    Luogu P4822 [BJWC2012]冻结
    Luogu P2575 高手过招(博弈论)
    Luogu P1074靶形数独
    Luogu P2323「皇后游戏」
    GodFly的寻宝之旅·状压DP
  • 原文地址:https://www.cnblogs.com/crazycode2/p/12081895.html
Copyright © 2020-2023  润新知