1. var name = "张三"
  2. function show(){
  3. console.log(this.name)
  4. }
  5. /* 函数正常调用的时候this指向window */
  6. function go(){
  7. var name = "李四"
  8. show();
  9. }
  10. window.go();//张三
  11. /* 函数要有对象去调用,事件也是需要对象去执行的 */

call、apply

call、apply 可以改变函数内部this关键字的指向

  1. var name = "王五";
  2. var obj = {
  3. name:"李四"
  4. }
  5. function go(){
  6. console.log(this.name)
  7. }
  8. go();
  9. go.call(obj);
  10. go.apply(obj);

当需传多个参数时

call 依次去传递
applay 需要传递数组

  1. var name = "window"
  2. var zhang = {
  3. name: "张三"
  4. }
  5. function show(a, b) {
  6. console.log(this.name);
  7. console.log(a + b)
  8. }
  9. show(1,2)
  10. //window
  11. //3
  12. show.call(zhang,2,3);
  13. //张三
  14. //5
  15. show.apply(zhang,[1,2])
  16. //张三
  17. //3

bind

  1. var name = "window"
  2. var zhang = {
  3. name: "张三"
  4. }
  5. var show = function(a,b){
  6. console.log(this.name)
  7. console.log(a+b);
  8. }.bind(zhang);
  9. show(2,3);
  10. //张三
  11. //5

使用场景

  1. <button id="btn">按钮</button>
  2. var id = "1001"
  3. var btn = document.getElementById("btn");
  4. btn.onclick = function(){
  5. // console.log(this.id)
  6. window.setTimeout(function(){
  7. console.log(this.id)
  8. },1000)
  9. }
  10. //点击btn输出1001,因为是window执行setTimeout方法,this指向window
  1. <button id="btn">按钮</button>
  2. var id = "1001"
  3. var btn = document.getElementById("btn");
  4. btn.onclick = function(){
  5. setTimeout(function(){
  6. console.log(this.id)
  7. }.bind(btn),1000)
  8. }
  9. //点击输出btn
  1. var id = "1001"
  2. var btn = document.getElementById("btn");
  3. btn.onclick = function(){
  4. var self = this;
  5. setTimeout(function(){
  6. console.log(this.id)
  7. }.bind(self),1000)
  8. }
  9. //点击输出btn
  10. var id = "1001"
  11. var btn = document.getElementById("btn");
  12. btn.onclick = function(){
  13. setTimeout(function(){
  14. console.log(this.id)
  15. }.bind(this),1000)
  16. }
  17. //点击输出btn

箭头函数

  1. var id = "1001"
  2. var btn = document.getElementById("btn");
  3. btn.onclick = function(){
  4. setTimeout(()=>{
  5. console.log(this.id)
  6. },1000)
  7. }
  8. //点击输出btn