apply bind call 和 this
阿新 • • 發佈:2018-05-31
方式 hat nbsp wrap http AR function TE true
Javascript裏面的this由調用方式確定它的指向。
1. 函數
此時為this為
function log() { console.log(this); } log();
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‘.
function log() { console.log(this); } log.call({name:"test call"}); log.apply({name:"test apply"}); log.bind({name:"test bind"})()
下面是一個簡單的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