函数调用的时候会执行call()方法
function get(content){
console.log(content)
}
get('xixi');
get.call(window,'xixi');
函数作为对象的方法被调用时也会执行call()方法
var person = {
name:'张三',
run:function(time){
console.log(this.name,time);
}
}
person.run(2)
person.run.call(person,2)
案例:谁调用this就指向谁
var name = 222;
var a = {
name:111,
say:function(){
console.log(this.name);
}
}
var fun = a.say;
fun(); // fun.call(window) 222
a.say(); //a.say.call(a) 111
var b = {
name:333,
say:function(fun){
fun() //fun.call(window)
}
}
b.say(a.say); // 222
b.say = a.say;
b.say() //b.say.call(b) // 333
箭头函数中的this
箭头函数没有自己的this
箭头函数中的this指向 定义箭头函数 所在的代码块的 外层的this
var obj = {
x: 222,
say:function(){
var one = ()=>{
console.log(this.x)
}
one()
}
}
obj.say() //222
var obj = {
x: 222,
say:function(){
var x = 111;
var obj2 = {
x: 333,
one:()=>{ console.log(this.x)}
}
obj2.one()
}
}
obj.say()//222
var x = 111;
var obj = {
x: 222,
say:()=>{
console.log(this.x)
}
}
obj.say(); //111
var a = 1
var obj = {
a:2,
getAge:function(){
var fn = ()=>this.a;
return fn()
}
}
obj.getAge() //2