this

2016-09-21  本文已影响27人  coolheadedY
var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() //John:hi!
var john = { 
  firstName: "John" ;
  sayHi: function func() { 
          alert(this.firstName + ": hi!")
        }
}
    func();//输出对象window,因为函数func()在window对象调用执行的

    function func() { 
      alert(this);
    }
function fn0(){
    function fn(){
        console.log(this);//输出window对象
    }
    fn();
}
fn0();//window
document.addEventListener('click', function(e){
    console.log(this);// 输出绑定事件的这个document对象
    setTimeout(function(){
        console.log(this);//输出window对象
    }, 200);
}, false);
//点击document后
//document
//window
var john = { 
  firstName: "John" 
}
function func() { 
  alert( this.firstName )
}
func.call(john) //输出John,这里用call函数改变func执行的作用域,使函数func在john对象中执行被调用.
var john = { 
  firstName: "John",
  surname: "Smith"
}
function func(a, b) { 
  alert( this[a] + ' ' + this[b] )
}
func.call(john, 'firstName', 'surname') //输出John Smith,这里用call函数改变func执行的作用域并传递两个参数,指定执行john对象下向对应的方法
var module= {
  bind: function(){
    $btn.on('click', function(){
      console.log(this) //this指什么
      this.showMsg();
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}

修改如下

var module= {
  var _this = this//用局部变量_this把this保存下来以便后面使用
  bind: function(){
    $btn.on('click', function(){
      console.log(_this) //this指的是被绑定事件的$btn对象
      _this.showMsg();//使用局部变量_this执行module对象下的方法
    })
  },
  
  showMsg: function(){
    console.log('饥人谷');
  }
}

本博客版权归 本人和饥人谷所有,转载需说明来源

上一篇下一篇

猜你喜欢

热点阅读