zoukankan      html  css  js  c++  java
  • this指向与更改this指向的方法

    &1.this指向window

    function apple(){

    console.log(this);//window

    }

    apple();

    &2.this指向实例化对象p1,p2;
    function Person(age,name){

      this.age = age;

      this.name = name;

    console.log(this)//Person

    }

    var p1=new Person(18,"dzj");

    var p2 = new Person(20,"dfj");

    &3.this指向该方法所属的对象

    var obj = {

       fn:function(){

        console.log(this)//obj

       }

    }

    obj.fn();

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

    <button id="btn">点击</button>

    <script>

    var myObtn=document.getElementById("btn");

    myObtn.onClick = function(){

    console.log(this)//<button id="btn">点击</button>

    }

    </script>

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

    setInterval(function () {
    console.log(this)
    },2000)

    *********************更改this指向的方法***********************

    &6.call()让this不指向window,指向Person

    var   Person={

      name:"dzj",

      like:"韩剧TV"

    };

    function demo(a,b){

    console.log(a,b)//李易峰 真帅气

    console.log(this);//{name:"dzj",like:"韩剧TV"}

    //不用call()方法,this指向window;用call()方法,this指向Person;

    }

    demo.call(Person,"李易峰","真帅气")

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

    var   Person={

      name:"dzj",

      like:"韩剧TV"

    };

    function demo(a,b){

    console.log(a,b)//4 5

    console.log(this);//{name:"dzj",like:"韩剧TV"}

    //不用apply()方法,this指向window;用apply()方法,this指向Person;

    }

    demo.apply(Person,[4,5])

  • 相关阅读:
    第十三周课程总结
    第十二周课程总结
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周课程总结&实验报告(四)
    第五周课程总结&试验报告(三)
    课程总结
  • 原文地址:https://www.cnblogs.com/dzj1/p/10751962.html
Copyright © 2011-2022 走看看