javascript this关键字

大部分来自《javascript学习指南》
1)在函数中this的使用:

<script>
const o = {
name:'zdd',
bark: function() { alert(this.name)}
}
o.bark();//zdd
</script>

当调用o.bark() 时候,this关键字跟o进行了绑定:
o.bark() 执行了alert (o.name)

如何绑定this是由方法如何被调用所决定的,而非函数定义所决定。也就是说,在这里,this绑定到o上并不是因为bark是o的属性,而是因为它直接由o调用(o.bark).如果把同一函数赋值给一个对象,会发生什么呢?
<script>
const o = {
name:'zdd',
bark: function() { alert(this.name)}
}
speak = o.bark;
alert(speak === o.bark);//true;两个变量都执行同一函数。
speak();//输出为一片空白,而不是zdd。

</script>
由于调用函数的方式,javascript并不知道原始函数是在o里面定义的,所以this将会绑定上undefined



调用、请求和绑定:

在javascript中,还允许指定this绑定的值,不论函数在何处被如何调用。从call讲起,call方法在所有函数上都可用,他还允许使用指定的this来调用函数。

call
apply:和call的主要区别,就是call会像一般函数一样直接获取参数,apply则会以数组方式获取参数
bind:永久绑定。给函数绑定一个永久的this值就不能在使用call,apply,bind了。


<script>
const o = {name:'zdd'};
const k = {name:'xiaodandan'};
function printName(){
    document.write("Im:"+this.name+"<br />");
}
printName();
printName.call(o);
printName.call(k);
</script>

输出:
Im:
Im:zdd
Im:xiaodandan

call方法的第一个参数是想要的绑定的值,剩下的参数则变成了要调用的函数的参数:

<script>
//*********不用管这段代码,obj2string就是将对象打印出来的*********************
//http://www.jb51.net/article/73498.htm
function obj2string(o){ 
 var r=[]; 
 if(typeof o=="string"){ 
 return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\""; 
 } 
 if(typeof o=="object"){ 
 if(!o.sort){ 
  for(var i in o){ 
  r.push(i+":"+obj2string(o[i])); 
  } 
  if(!!document.all&&!/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){ 
  r.push("toString:"+o.toString.toString()); 
  } 
  r="{"+r.join()+"}"; 
 }else{ 
  for(var i=0;i<o.length;i++){ 
  r.push(obj2string(o[i])) 
  } 
  r="["+r.join()+"]"; 
 } 
 return r; 
 } 
 return o.toString(); 
};
//***********************************end************

const bu = {name:'joker'};
function update(birth,age){
    this.birth = birth;
    this.age = age;
}
update.call(bu,1994,24);
alert(obj2string(bu));//输出:{name:"joker",birth:1994,age:24}
</script>

可见:对象增添了两个属性。
如果是apply进行绑定的话:

update.apply(bu,[1994,24]);//此外和call没啥差别。

一个经典的示例:找出数组中的最大值和最小值。内建的Math.max和Math.min函数可以接受任意一串数字作为参数,并分别返回最大值和最小值。

const a = [1,2,3];
Math.min.apply(null,arr);//1

这里给this传了一个null,因为他们并不适用this。

const a = [1,4,9,0,2]
alert(Math.min(...a));

Array.prototype.max = function(){ 
return Math.max.apply(1,this) 
} 
Array.prototype.min = function(){ 
return Math.min.apply(null,this) ;//这里的this和上面的this千万别搞混啊。
} 
alert([1,2,3].max());// => 3 
alert([1,2,3].min());// => 1

还有一个bind,bind就暂时不说了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值