this

作者: 郑宋君 | 来源:发表于2019-03-06 19:53 被阅读0次
    var name = 'hello world'
    var app = {
      name : 'apple',
      sayName : function(){
        console.log(this.name)
      }
    }
    
    
    var obj = {
      name :'objName'
    }
    
    app.sayName.bind()()  || app.sayName.bind('window')()      //hello world
    app.sauName.bind(obj)()       // objName
    //bind 返回的是一个新的函数 所以后面要加上()
    

    函数名+ bind(对象名)()
    他的意思表名返回一个新的函数,执行的还是函数名的函数体,但是内部this的指向是对象名这个对象

    var page = {
      init:function(){
        this.node = document.body
        this.bind()
      },
      
      bind:function(){
        this.node.addEventListener('click',this.sayHello.bind(this))
      },
      
      sayHello:function(){
              
        console.log('hello...'+this.node.innerText)
      }
    }
    
    page.init()
    

    相关文章

      网友评论

          本文标题:this

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