this

  • apply、call 有什么作用,什么区别

  • 使用call和apply方法,可以改变对象方法的运行环境。

  • call 和 apply 都可以改变函数执行时的上下文环境,也就是指定了函数体内部 this 的指向。

  • call 和 apply 的区别:call和apply区别在于接受参数的形式不同。
    function.call(obj,arg1,arg2,arg3, ...);接受逐个参数
    function.apply(obj,[arg1,arg2..]);接受的是数组形式的参数

  • this最直白的解释(新增待填)

  • 以下代码输出什么?

var john = { 
  firstName: "John" 
}
function func() { 
  alert(this.firstName + ": hi!")
}
john.sayHi = func
john.sayHi() //John:hi!
  • 可以理解成对象john添加了一个sayHi的属性,对象john在sayHi方法里执行了func().所以this环境是对象john
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
  • 下面代码输出什么,why
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('饥人谷');
  }
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. apply、call 、bind有什么作用,什么区别? call ,apply的作用:调用一个函数,传入函数...
    Rising_suns阅读 403评论 0 0
  • 作业 this 相关问题 问题1: apply、call 有什么作用,什么区别apply()和call()函数都可...
    饥人谷_桶饭阅读 402评论 0 0
  • apply、call 、bind有什么作用,什么区别 apply:fn.apply( obj,])将fn函数里的t...
    邵志远阅读 549评论 0 0
  • apply、call 有什么作用,什么区别 首先要引入this这个概念由于运行期绑定的特性,this的含义非常多,...
    块垒阅读 201评论 0 0
  • this 相关问题 apply、call 、bind有什么作用,什么区别这三个方法均可以改变调用函数的this指向...
    放风筝的小小马阅读 384评论 0 1