改变函数内this指向 js提供了三个方法
var o = {
name:"hello"
}
function fn(a,b){
console.log(this)
console.log(a+b);
}
fn.call(o,4,5)
call 可以调用函数 还可以改变函数内的this指向
call的主要作用可以实现继承
function Father(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Son(name,age,sex){
Father.call(this,name,age,sex);
}
var son = new Son("hh",12,"男");
console.log(son)
运用的意思
var o = {
name:"hello"
}
function fn(arr){
console.log(this)
console.log(arr); //yellow
}
fn.apply(o,['yellow']);
- apply()可以调用函数 还可以改变函数内的this指向
- 它的参数必须是数组,调用的函数会将数组中的所有元素作为参数接收,可以通过arguments查看
- 和一般函数一样,如果传入的参数多于形参,只取前面的;如果少于,未传入的为undefined。
apply似乎也可以像call一样用来继承
/*定义一个人 类*/
function Person(name,age)
{
this.name=name;
this.age=age;
}
/*定义一个学生 类*/
function Student(name,age,grade)
{
Person.apply(this,arguments);
this.grade=grade;
}
//创建一个学生类
var s = new Student("zhangsan",21,"一年级");
//测试
console.log(s.name,s.age,s.grade);
//可以看到测试结果 zhangsan,21,一年级
this指向s
arguments:[“zhangsan”,”21”,”一年级”];
可以利用apply传参 将数组拆散成单个元素 传输的特点,实现和扩展运算符相似的功能:
我们可以利用apply 比如借助于数学内置对象 求数组的最大值
// Math.max(值1,值2,值3,值4)
var arr = [1,34,56,3,2];
var max = Math.max.apply(null,arr);
var min = Math.min.apply(null,arr);
console.log(max,min)
使用扩展运算符做同样事情:
var arr = [1,34,56,3,2];
var max = Math.max(…arr);
var min = Math.min(…arr);
console.log(max,min);
还是扩展运算符方便,哈哈哈
// bind() 绑定 捆绑的意思
var o = {
name:"hello"
}
function fn(a,b){
console.log(this)
console.log(a+b); //
}
var f = fn.bind(o,3,4);
// console.log(f)
f()
比如:需求 点击了按钮 就禁用按钮 3秒后开启这个按钮
var btn = document.querySelector("button");
btn.onclick = function(){
this.disabled = true; //this指向btn这个按钮
var that = this;
setTimeout(function(){
// btn.disabled = false
that.disabled = false;
},3000)
}
btn.onclick = function(){
this.disabled = true; //this指向btn这个按钮
setTimeout(()=>{
this.disabled = false;
},3000)
}
btn.onclick = function(){
this.disabled = true; //this指向btn这个按钮
setTimeout(function(){
this.disabled = false;
}.bind(this),3000)
}