call和apply调用的时候执行,而bind则是返回改变了函数运行的上下文环境,不会马上执行;call,apply的区别:他们俩之间的差别在于参数的区别,apply传递的数组, call依次传递
call和bind
function fn1(){ console.log(this); } var obj ={ name:'vue' } fn1() fn1.call(obj) var fn2 = fn1.bind(obj) fn2()
练习 // 2、作为对象的方法调用 // 3、箭头函数中this var name ="window" var obj = { name:"javaScript", sayName(){ console.log(this.name); //obj调用所有输出里面的name }, wait(){ // console.log(this.name);// 这个地方会输出里面的name setTimeout(function(){ console.log(this.name); //这里面还套了给setTime方法 所有输出的是window }) }, delay(){ setTimeout(()=>{ console.log(this.name); //使用了箭头函数 this指向谁就输出谁 }) }, layOut(){ setTimeout(function(){ console.log(this.name); }.bind(this)) //bind关键字改变了this关键字的指向 }, print(){ var that =this setTimeout(function(){ console.log(this.name); }.bind(that)) } } obj.sayName() obj.wait() obj.delay() obj.layOut() obj.print()
class this
// class this 指向实例化的对象 // 在class 和构造函数中this.指向使用关键字实例化的对象 class Person{ skill ="lisi" constructor(name,age){ this.name= name this.age = age console.log(this); } } var p = new Person("lisi",18) console.log(p.name);