1. callapply调用的时候执行,而bind则是返回改变了函数运行的上下文环境,不会马上执行;
  2. call,apply的区别:
  3. 他们俩之间的差别在于参数的区别,apply传递的数组, call依次传递

call和bind

  1. function fn1(){
  2. console.log(this);
  3. }
  4. var obj ={
  5. name:'vue'
  6. }
  7. fn1()
  8. fn1.call(obj)
  9. var fn2 = fn1.bind(obj)
  10. fn2()
  1. 练习
  2. // 2、作为对象的方法调用
  3. // 3、箭头函数中this
  4. var name ="window"
  5. var obj = {
  6. name:"javaScript",
  7. sayName(){
  8. console.log(this.name); //obj调用所有输出里面的name
  9. },
  10. wait(){
  11. // console.log(this.name);// 这个地方会输出里面的name
  12. setTimeout(function(){
  13. console.log(this.name); //这里面还套了给setTime方法 所有输出的是window
  14. })
  15. },
  16. delay(){
  17. setTimeout(()=>{
  18. console.log(this.name); //使用了箭头函数 this指向谁就输出谁
  19. })
  20. },
  21. layOut(){
  22. setTimeout(function(){
  23. console.log(this.name);
  24. }.bind(this)) //bind关键字改变了this关键字的指向
  25. },
  26. print(){
  27. var that =this
  28. setTimeout(function(){
  29. console.log(this.name);
  30. }.bind(that))
  31. }
  32. }
  33. obj.sayName()
  34. obj.wait()
  35. obj.delay()
  36. obj.layOut()
  37. obj.print()

class this

  1. // class this 指向实例化的对象
  2. // 在class 和构造函数中this.指向使用关键字实例化的对象
  3. class Person{
  4. skill ="lisi"
  5. constructor(name,age){
  6. this.name= name
  7. this.age = age
  8. console.log(this);
  9. }
  10. }
  11. var p = new Person("lisi",18)
  12. console.log(p.name);