this 指针归纳 javascript

栏目: C · 发布时间: 5年前

内容简介:一个函数中this的指向是由调用这个函数的环境来决定的。

概述

一个函数中this的指向是由调用这个函数的环境来决定的。

  1. 全局

    var a = 1;
    function b(){
        var a = 2;
        console.log(this.a);
    };
    b(); //1
    <input type="text" value="4" onclick="b()" />
    
    var value = 3;
    function b(){
        console.log(this.value);
    };
    b();//3
    此时的b函数的环境是全局的
  2. 局部

    var a = 1;
       var c = {a:3};
       c.b = function(){
       var a = 2;
       console.log(this.a);
       };
       c.b();//3
       
      //立即执行函数 由于是赋值,所以只执行了右边的函数
      var a = 1;
      var c = {a:3};
      (c.b = function(){
      var a = 2;
      console.log(this.a);
      })();//1

apply、call 和 bind 改变this指向

  1. apply

    • 参数

      只能传两个参数 ,第一个参数a是 改变this指向的结果对象(在非严格模式下,第一个参数为null或者undefined时会自动替换为指向全局对象) ,第二个参数是传给a的 参数集合(arguments[数组或类数组])

    • 实例

      var a = 1;
      var c = {a : 3};
      function b(d,e){
          var a = 2;
          console.log(this.a);
          console.log(d,e);
      };
      b.apply(c);//3  undefined undefined
      b.apply();//1  undefined undefined
      b.apply(c,[5,6]);// 3  5 6
  2. call

    • 参数

      第一个参数和apply()的第一个参数一样,不同的是apply()后面是接收一个数组或类数组,call()后面是是接收的参数列表。

    • 实例

      var a = 1;
      var c = {a : 3};
      function b(d,e){
          var a = 2;
          console.log(this.a);
          console.log(d,e);
      };
      b.call(c);//3  undefined undefined
      b.call();//1  undefined undefined
      b.call(c,5,6);// 3  5 6
  3. bind

    • 参数

      参数和call一样,不同的是 call()和apply()在调用函数之后会立即执行,而bind()方法调用并改变函数运行时上下文后,返回一个新的函数,供我们需要时再调用。

    • 实例

      var a = 1;
      var c = {a : 3};
      function b(d,e){
         var a = 2;
         console.log(this.a);
         console.log(d,e);
      };
      var b1 = b.bind(c);
      var b2 =b.bind();
      var b3 =b.bind(c,5,6);
      b1();//3  undefined undefined
      b2();//1  undefined undefined
      b3()// 3  5 6

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Cult of the Amateur

The Cult of the Amateur

Andrew Keen / Crown Business / 2007-6-5 / USD 22.95

Amateur hour has arrived, and the audience is running the show In a hard-hitting and provocative polemic, Silicon Valley insider and pundit Andrew Keen exposes the grave consequences of today’s......一起来看看 《The Cult of the Amateur》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试