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

    this是javascript语言中的一个关键字,它是函数运行时自动生成的一个内部对象,只能在函数内部使用。一般情况下,this指向的是调用函数的那个对象。

    (1)作为普通函数直接调用,this指向window

    function fun(){
      this.age = 1;
    }
    fun();

    函数fun中的this指向是window,即

    function fun(){
      this.age = 1;
    }
    fun();
    console.log(age);//输入1

    这里的age相当于全局变量age,能被其他函数调用,如果代码改为

    function fun(){
      var age = 1;
    }
    fun();
    console.log(age);//报错,age is not defined,这里的age是fun()中的局部变量

    还有一种函数调用,及嵌套函数:

    function fun(){
      function inner(){
        this.age = 1;      
      }
      inner();
    }
    fun();
    console.log(age);//输入1

    这里的this指向仍然是window,即还是全局变量,但此处的inner()是fun()中的对象,不能直接在fun外调用。

    (2)作为对象方法调用

    var age = 2;    
    var test = {
      age: 1,
      show: function(){
        console.log(this.age);//输出1,此处的this指向的是test对象
      }
    }
    console.log(this.age);//输出2,此处的this指向的是window,并不受test对象age的影响
    test.show();

    (3)作为构造函数调用

    构造函数是指通过这个函数生成一个新的对象。这时,this指向这个新的对象。

    var age = 2;    
    function test(){
      this.age = 1;
    }
    var tt = new test();
    tt.show = function(){
      console.log(this.age);//输出1,此时this指向tt
    }
    tt.show();
    console.log(this.age);//输出2,由此可见,构造函数中的this不会影响到全局变量

    (4)call/apply 调用,改变this的指向

    var age = 1;
    function show(){
      this.age = 3;
    }
    function test(){
      this.age = 2;
    }
    show.call(test);//test继承了show里的方法及属性,此时,show中的this指向的是test
    console.log(test.age);//输出3

    还有一些this,比如在click事件中,this指向的是操作的节点元素;ajax中的this指向的就是ajax里的内部对象了。

  • 相关阅读:
    json to dictionary
    ie下 频繁异步加载导致崩溃
    如何实现数据在表内部置顶
    js货币转换,replaceAll写法
    js奇怪的问题
    mssql中public和db_owner权限下拿到webshell或者系统权限
    关于Alexa Toolbar的破解方法
    如何备份和还原 IIS
    WIN下IIS备份与恢复操作
    汽车品牌标志数据库
  • 原文地址:https://www.cnblogs.com/cyj7/p/5164255.html
Copyright © 2011-2022 走看看