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
    水到渠成,相信积累的力量!
  • 相关阅读:
    关于Xcode的一些方法-15-05-01
    iOS 多线程(NSThread、GCD、NSOperation)
    iOS中View的创建过程
    iOS启动原理及应用生命周期
    UITableView详解
    iOS 字典转模型
    strong和weak
    零碎知识点总结(不定时更新)
    iOS常用第三方类库 Xcode插件
    cocoapods 类库管理利器
  • 原文地址:https://www.cnblogs.com/popstar8866/p/6527767.html
Copyright © 2011-2022 走看看