js中 call()与apply()方法 和 bind()方法

call与apply都属于Function.prototype(即原型对象身上的方法)的一个方法,所以每个function实例都有call、apply属性;

call()和apply() 是静态方法,这里面有详细的解释 是构造函数的方法,

作用

call()、apply()、bind() 都是用来重定义 this 这个对象的!

区别

call():第一个参数是this值没有变化,变化的是其余参数都直接传递给函数。在使用call()方法时,传递给函数的参数必须逐个列举出来。

apply():传递给函数的是参数数组

1 function add(c, d){ 
2     return this.a + this.b + c + d; 
3 } 
4 var o = {a:1, b:3}; 
5 add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 
6 add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34 

 

 1 function People(name, age) {
 2     this.name = name;
 3     this.age = age;
 4 }
 5 
 6 function Student(name, age, grade) {
 7     People.call(this, name, age);
 8     this.grade = grade;
 9 }
10 
11 var student = new Student('小明', 21, '大三');
12 console.log(student.name + student.age + student.grade);//小明21大三

bind()方法

https://blog.csdn.net/m0_38060839/article/details/83508863

 1 mounted() {
 2     this.getindex().then((res) => {
 3       console.log(res, '111111')
 4     })
 5   },
 6   methods: {
 7     getindex() {
 8         
 9       // return new Promise((reslove, reject) => {              //箭头函数无需绑定this
10       //   setTimeout(() => {
11       //     reslove(this.handlename)
12       //   }, 1000)
13       // })
14 
15       return new Promise(function(reslove, reject) {
16         setTimeout(() => {
17           reslove(this.handlename)
18         }, 1000);
19       }.bind(this))                                           // 普通函数绑定this
20 } }

 

posted @ 2020-08-13 11:13  顺·  阅读(603)  评论(0编辑  收藏  举报