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

    js中 this的指向一共存在3种地方:

    1.全局的this;

    2.构造函数的this;

    3.call/apply;

    一、全局的this:

     1 function test(){
     2     this.d = 3;//函数的默认指向是window
     3     var a = 1;
     4     function c(){
     5     }
     6 }
     7 
     8 test(123);
     9 console.log(window.d);
    10 console.log(this.d);//this 默认指向window

    这里有两个点:函数的默认指向是window;全局this 指向 window;

    预编译的过程:

     ao:
         this : window
         a
         c :function c(){}
        
        go:
            test :function test(){}

    这里的两个console.log输出的都是3

    二、构造函数中this的指向:

    1     function Test(){
    2         this.name = "123";
    3         }
    4     var test = new Test();

    这里的预编译过程是这样的:

    GO:Test :function Test(){};

    AO:

    第一次:this {window};

    当new了之后: this : {name:123; __proto__:Test.prototype}

    三、call/apply改变this的指向

     1 //call/apply 改变this指向
     2 function Person(){
     3         this.name = "张三";
     4         this.age = 18
     5     }
     6 function Programmer(){
     7     Person.apply(this);
     8     this.work = "Progarmming";
     9 }    
    10 
    11 var p = new Programmer();
    12 console.log(p);

    根据前面的介绍,可知:Person.apply(this);中this 是指向Programmer的实例化对象,  此处 的this也替换了Person 实例化对象;所以 最后输出就是:
    {name: "张三", age: 18, work: "Progarmming"}

    总结:

    1.全局this 指向 window

    2.预编译函数 this指向window

    3.构造函数的this 指向实例化对象

    4.apply/call改变this的指向

    补充:js中 this 和 $(this)的区别

    this是html中返回的类集合([object HTMLImageElement]),而$(this)返回的是Jquery的集合([object Object ])

    以下例子是以https://www.miaov.com/网站为页面的一个例子;

     1 $(".menu ul").each(function(){
     2 var a = $(this);
     3 var b = this
     4 //test(a.text());
     5 debugger
     6 test(b.innerText);
     7 })
     8 
     9 function test(obj){
    10 alert(obj);
    11 }

    这里当获取 ul的值,两种方式去取;


     

  • 相关阅读:
    深入理解HTTP Session
    java中使用队列:java.util.Queue
    throws/throw Exception 异常应用
    Log4j实现对Java日志的配置全攻略
    java中volatile关键字的含义
    hibernate调用oracle存储过程||函数
    手势仿QQ侧滑---秀清
    归档和解档---秀清
    全局定义UINavigationContoller--By秀清
    重力感应 加速计- By严焕培
  • 原文地址:https://www.cnblogs.com/lixiuming521125/p/11133265.html
Copyright © 2011-2022 走看看