apply bind call 和 this

努力尽今夕,少年犹可夸。这篇文章主要讲述apply bind call 和 this相关的知识,希望能为你提供帮助。
javascript里面的this由调用方式确定它的指向。
1. 函数
此时为this为window

function log() { console.log(this); } log();

 
apply bind call 和 this

文章图片

 
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

文章图片

 
但我们可以通过使用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

文章图片

 
下面是一个简单的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

文章图片

【apply bind call 和 this】 

    推荐阅读