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>
posted @ 2019-12-21 18:05  懵智  阅读(1101)  评论(0编辑  收藏  举报