call,apply,bind的用法及区别
2024-08-22 11:36:21
<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>
最新文章
- Form 表单提交参数
- LInux MySQL 端口验证
- 一、CoreAnimation之图层树详解
- Android View和ViewGroup
- CF 213A Game(拓扑排序)
- 磁盘IO的性能指标
- IOS多线程(GCD)
- 2016年5月19日php,mysql配置
- HashTable、HashMap、LinkedHashMap、TreeMap的比较
- java使用maven创建springmvc web项目
- 新版iTunes如何设置手机铃声
- Azure IoT 技术研究系列5-Azure IoT Hub与Event Hub比较
- 算法题丨3Sum Closest
- 微软与开源干货对比篇_PHP和 ASP.NET在 Session实现和管理机制上差异
- 用golang写了个统计各单位报送的信息数量的微服务
- Redis学习-set数据结构
- 鸟哥的Linux私房菜——第十九章:例行命令的建立
- GoF--服务定位器模式
- requests爬取百度音乐
- 比較JS合并数组的各种方法及其优劣