美文网首页
this指针的用法

this指针的用法

作者: 想回到童年 | 来源:发表于2017-11-22 21:10 被阅读0次

    概念

    this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
    1.只有函数调用,this只想window

    function name() { 
      console.log(this)    
    }
    name()     输出window
    

    2作为对象的方法调用,谁最后调用它,this指向谁。

    function name() { 
      console.log(this.name)    
    }
    function getName(name) {
      this.name  = name
    }
    var student = new getName("王")
    name.call(student)  输出王
    

    3 构造函数this
    构造函数创建出来的对象this就只想该对象
    4 call
    指向后面改变的对象

    相关文章

      网友评论

          本文标题:this指针的用法

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