源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

函数四种调用模式以及其中的this指向

  • 时间:2020-11-13 08:28 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:函数四种调用模式以及其中的this指向
[b]第一种:函数直接执行模式[/b]
function add(a,b){
   console.log(this);
   return a+b;
  }
 add(10,20)//this===window
[b]第二种:对象方法的调用模式[/b]
var obj={
   name:'aaa',
   age:20,
   said:function(){
    console.log(this);
   }
  }
obj.said();//this===obj,此处this指代被调用者
[b]第三种:构造器的调用模式[/b]
function School(){
   this.said=function(){
    console.log(this);
   }
  }
var nanj=new School();
nanj.said();//对象调用自己的方法,this===nanj,类似上面
[b]第四种:call和apply调用模式[/b]
function change(a,b){
   this.detial=a*b;
   console.log(this);
  }
  var p={};
  change.call(p,4,5);//此处的this===p
  console.log(p.detial);
  var q=[];
  change.call(q,5,10)//this===q
  console.log(q.detial);
  //apply和call一样的用法,只不过apply第二个参数用数组进行传递
  var arr=[];
  change.apply(arr,[10,10]);//this===arr
  console.log(arr.detial);
  var str={};
  change.apply(str,[20,20]);//this===str
  console.log(str.detial);
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程素材网!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部