JavaScript中的this

前段时间回答的一个关于this的问题,便总结记录下。
在javascript的函数中,除了声明时定义的形参以外,每一个函数还能够接收两个附加的参数:this和arguments。这里就讲一下this的做用以及不一样场景下它的不一样指向。this的取值(即它的指向取决于调用的模式),在javascript中明确this指向大体有四种状况:javascript

1.函数调用模式的时候,this指向windowjava

function aa(){
  console.log(this)
}
aa()                 //window

2.方法调用模式的时候,this指向方法所在的对象segmentfault

var a={};
a.name = 'hello';
a.getName = function(){
  console.log(this.name)
}
a.getName()         //'hello'

3.构造函数模式的时候,this指向新生成的实例app

function Aaa(name){
  this.name= name;
  this.getName=function(){
    console.log(this.name)
  }
}
var a = new Aaa('kitty');
a.getName()        //  'kitty'
var b = new Aaa('bobo');
b.getName()        //  'bobo'

4.apply/call调用模式的时候,this指向apply/call方法中的第一个参数函数

var list1 = {name:'andy'}
var list2 = {name:'peter'}

function d(){
  console.log(this.name)
}
d.call(list1)     //  'andy' 
d.call(list2)     //  'peter'
相关文章
相关标签/搜索