this

作者: chengfengwang | 来源:发表于2017-05-28 22:58 被阅读0次

    this是什么

    • 可以近似地认为,this是所有函数运行时的一个隐藏参数,指向函数的 运行环境
    • 看this指向谁,要看函数运行时所在的对象

    不同的情况

    • 构造函数中的this,指的是所要生成的实例对象。
    • 当函数被用作事件处理函数时,它的this指向触发事件的元素

    call方法注意点

    • call方法的参数,应该是一个对象(typeof 参数a == "object")

    一些题目

    function f() {
      return '姓名:'+ this.name;
    }
    var A = {
      name: '张三',
      describe: f
    };
    var B = {
      name: '李四',
      describe: f
    };
    
    A.describe() // "姓名:张三"
    B.describe() // "姓名:李四"
    //函数作为对象的方法调用,指向对象
    
    var A = {
      name: '张三',
      describe: function () {
        return '姓名:'+ this.name;
      }
    };
    
    var name = '李四';
    var f = A.describe;
    f() // "姓名:李四"
    //函数运行时所在环境是window
    
    function Person(name,age){
        this.name=name;
        this.age=age
    }
    function Student(name,age,sex){
        this  //this绑定对象
        Person.bind(this)(name,age)//执行Person函数,把参数传递进去,只不过this是下面的对象 s
    }
    var s=new Student('wang',2,'boy')//当new对象的时候,第一步创建空对象第二会执行Student函数,遇到了Person函数,去执行Person函数,这时的this是对象
    

    this在window环境下调用,指向全局变量

    var x = 1;
    function test(){
      alert(this.x);
    }
    test(); // 1
    

    作为对象方法调用,指向此对象

    var a = {
      name:'wang',
      f:function(){return this.name}
    }
    a.f() // wang
    

    构造函数里的this zhi'xi

    相关文章

      网友评论

          本文标题:this

          本文链接:https://www.haomeiwen.com/subject/tiihfxtx.html