分享

JavaScript中的this

 只怕想不到 2015-09-02

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

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

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

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

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

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

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' 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多