努力尽今夕,少年犹可夸。这篇文章主要讲述apply bind call 和 this相关的知识,希望能为你提供帮助。
javascript里面的this由调用方式确定它的指向。
1. 函数
此时为this为window
function log() { console.log(this); } log();
![apply bind call 和 this](http://img.readke.com/220504/01142060W-0.jpg)
文章图片
2. 对象方法
此时为实例对象。
function log() { console.log(this); }function class1() { this.name="class1 name" }var obj1=new class1(); obj1.fu1=log; obj1.fu1();
![apply bind call 和 this](http://img.readke.com/220504/0114203492-1.jpg)
文章图片
但我们可以通过使用apply,bind,call来指定‘this‘.
function log() { console.log(this); } log.call({name:"test call"}); log.apply({name:"test apply"}); log.bind({name:"test bind"})()
![apply bind call 和 this](http://img.readke.com/220504/0114202X1-2.jpg)
文章图片
下面是一个简单的bind实现,可以帮助理解。
Function.prototype.bind2 = function(context){ var _that = this; return function() { _that.apply(context); }; }function fn1() { console.log(this); }var fn2=fn1.bind2({name:"testing"}); fn2();
![apply bind call 和 this](http://img.readke.com/220504/0114202325-3.jpg)
文章图片
【apply bind call 和 this】
推荐阅读
- springmvc配置中,mapper一直依赖注入不进去的问题记录
- Android_(消息提示)多种使用Toast的消息提示
- Android安全编码
- 五步打造APP节日主题设计(以Lofter新年图标设计为例)
- 事件(Application Event)
- CS294-112 深度强化学习 秋季学期(伯克利)NO.20 Guest lecture: John Schulman (PPO and Applications)
- android Studio 二维码扫一扫 使用精简过的zxing
- 学编程,学java还是大数据android(平均月薪23k以上告诉你方向)
- Android(制作聊天气泡点9图)