call,apply,bind的用法及區別


<script>

function test(){
console.log(this)
}
// new test();
//函數調用call方法的時候,就會執行。
//call的參數:第一個參數:方法執行的時候,方法中的this的指向。第二個參數:表示方法執行所需要的實際參數。
var obj ={ name:"zhagafd"};
// test.call(obj,"hello");
//applly的參數:第一個參數:方法執行的時候,方法中this的指向。第二個參數:方法執行的時候,所有形參的一個數組[];
test.apply(obj,["hello"]);
//bind方法的特點:綁定方法執行時的this,並沒有馬上執行,而是返回一個方法對象
//bind方法傳實際參數的方法與call一致
var foo = test.bind(obj,"hello");
foo();
 
//繼承
function person(name,age){
this.name = name;
this.age = age;
this.eat = function(){
console.log('eating...');
}
this.show = function(){
console.log(name+''+age);
}
}
//定義一個student類,繼承person
function stundent(name,age,score){
this.score = score;
person.call(this,name,age);
}
//實例化student
var stu = new stundent('tom',18,88);
stu.eat();
stu.show();
 
//回調函數的this指向指定后,並沒有馬上去執行,所以當需要指定回調函數的this時,使用bind方法來實現
var obj = {name:"zhangsan"};
setTimeout(function(){
console.log(this);
}.bind(obj),100)
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM