关于JS中函数调用中的this指向
#关于JS中函数调用中的this指向
##JS中函数有4种调用方法
###方法调用模式
```
var student = {
name:'zhangsan',
sayHello:function(){
console.log('hello'+this.name)
}
}
这里的this指向调用该方法的对象student
```
```
var student = {
name:'zhangsan',
sayHello:function(){
console.log('hello'+this.name)
}
}
var man = {name : 'man'};
man.say = student.sayHello;
man.say();
这里的this就指向了man对象 因为是man调用的该方法
```
###函数调用模式
```
var student = function(){
console.log(this);
}
student();
window.student();
这里的this指向window
```
###构造器调用模式
```
function student(){
console.log(this);
}
student.prototype.say = function(){
console.log(this);
}
var stu = new student();
stu.say();
指向的是构造函数new出来的对象
```
###上下文调用模式
```
var foo = function(a,b){
console.log(this);
return a+b;
}
var arr = [1,2];
var arr1 = [];
var sum = foo.apply(arr1,arr)
console.log(sum)
这里的this指向的是apply(call)中的第一个参数arr1
```

浙公网安备 33010602011771号