zoukankan      html  css  js  c++  java
  • Javascript学习之 this关键字

    This关键字

      1.在全局执行上下文(在任何函数之外),this指的是全局对象;浏览器端 this===window;node端 this===global;在函数执行上下文中,视具体情况;

      2.当函数在其主体中使用关键字this时,它的值可以使用所有函数继承callapply方法绑定到调用中的特定对象。

    function add(c, d) {
      return this.a + this.b + c + d;
    }
    var o = {a: 1, b: 3};
    add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
    add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
     function f4() {
          this.herp = 'derp';
        }
      function Thing() {
        this.thisIsEasyToUnderstand = 'just kidding';
        f4.call(this);
      }
      var thing = new Thing(); 
      // thing = {thisIsEasyToUnderstand: 'just kidding', herp: 'derp'};
    实现了this从一个上下文传递到另一个上下文中

      通过使用add函数的call方法,将add函数内部的this指向o对象,这就达到了将this从一个上下文传递到另一个上下文中的作用;call方法与apply几乎一样,只不过参数不同,

    call方法:第一个参数为this指向的对象,后面是众多的参数列表;

    apply方法:第一个参数为this指向的对象,后面是一个单独的参数数组;

      3 this作为对象的情况:当一个函数作为一个对象的方法时,该函数内部的this指向该函数外层最近的对象;

    var o = {
      prop: 37,
      f: function() {
        return this.prop;
      }
    };
    console.log(o.f()); // logs 37
    水到渠成,相信积累的力量!
  • 相关阅读:
    入门OJ 4187【周末舞会】
    入门OJ 1532【排队取款】
    洛谷 P3029 [USACO11NOV]【牛的阵容Cow Lineup】
    洛谷 P1638【逛画展】
    入门OJ 1256【排队】
    PKU 1945【Power Hungry Cows】
    RocketMQ重试机制和消息
    Java操作RocketMQ
    RocketMQ概述
    重定向机制
  • 原文地址:https://www.cnblogs.com/popstar8866/p/6527767.html
Copyright © 2011-2022 走看看