函数
函数的定义方式
- 自定义函数(命名函数)
- 函数表达式(匿名函数)
- 利用
new Function("参数1","参数2","函数体")
注意:所有函数都是Function的实例
this的指向
调用方法 | this指向 |
---|---|
普通函数调用 | window |
构造函数调用 | 实例对象,原生对象中的方法也是指向实例对象 |
对象方法调用 | 该方法所属对象 |
事件绑定方法 | 绑定事件对象 |
定时器函数 | window |
立即执行函数 | window |
// 普通函数 this指向window对象
function fun1(name){
this.name = name
console.log(this);
}
// 构造函数 this指向构造函数的实例对象
function Student(name,age){
this.name = name;
this.age = age;
console.log(this);
// 方法
this.sing = function(){
console.log("唱跳rap");
console.log(this);
}
}
// 对象方法 this指向所属对象
var obj = {
fun2 : function(){
console.log(this);
console.log("对象方法");
}
}
// 绑定事件的函数 this指向的是事件绑定的元素
// 获取元素
let btn = document.querySelector("button");
// 绑定事件
btn.addEventListener("click",function(){
console.log("点击了绑定事件",this);
},false)
// 定时器函数 this指向的是window对象
setTimeout(function(){
console.log("定时器",this);
},1000)
// 立即执行函数 this指向的是window对象
(function(){
console.log("立即执行函数",this);
})()
// 运行函数
fun1.call()
let zhaoshun = new Student("赵舜",12);
console.log(zhaoshun.sing);
obj.fun2()
改变this指向的方法
call方法
-
call()可以调用函数
-
call()可以改变这个函数的this指向,此时这个函数的this就指向了call()里面的第一个对象
// 定义函数 function fn(x,y){ console.log("我想吃芒果"); console.log(this); console.log(x+y); } // 定义对象 var obj = { name:"jesse" } // 调用函数 fn.call() // 可以改变这个函数的this指向 fn.call(obj,1,2)
fn.call()
中的this指向的是window对象fn.call(obj,a,b)
中的this指向的是obj对象
apply方法
fun.apply(thisArg,[argsArray])
thisAry
:在fun函数运行时,指定的this值argsArray
:传递的值,必须包含在数组中- 返回值就是函数的返回值,因为他就是调用函数
// 定义一个函数
function fun(){
console.log(this);
}
// 定义一个对象
var obj = {
name:"zhaoshun",
age:12
}
// this指向的是obj对象
fun.apply(obj)
运行结果:
{
name: "zhaoshun"
age: 12
}
注意:
- apply也是调用函数,第二个参数可以改变函数内部的this指向
- 第二个参数必须是数组
- apply的主要应用,可以借助apply求得数组的最值
bind方法
bind()
方法不会调用函数,但是会改变函数内部this的指向。
fun.bind(thisArg,arg1,arg2,...)
thisArg
:在fun函数运行时指定的this值arg1,arg2
:传递的其他参数- 返回由指定的this值和初始化采纳数改造的原函数的拷贝
// 定义一个函数
function func(a,b){
console.log(this);
console.log(a+b);
}
// 定义一个对象
var obj = {
name:"zhaoshun",
age:12
}
// this指向的是obj对象
fun.apply(obj);
// bind改变func函数的this指向,同时返回的是改变this之后的产生的新函数
var f = func.bind(obj,1,2);
// 运行函数
f()
应用在定时器中:
// 获取元素
var btn = document.querySelector("button");
btn.addEventListener("click",function(){
console.log("打印了",this);
// 当点击了按钮之后将其进行禁用
this.disabled = true
// 加一个定时器,定时进行解除禁用
setTimeout(function(){
this.disabled = false
console.log("解除了禁用");
//此处的this在定时器外面,因此this指向的是btn这个事件绑定的对象
}.bind(this),3000)
})
call方法
call、apply、bind方法总结
属性 | 异同 |
---|---|
相同点 | 都可以改变函数内部的this指向 |
区别点 | call和apply会调用函数,并且改变函数内部this指向。call和apply传递的参数不一样,call传递参数arg1 ,arg2 …形式,apply必须是数组形式[args]。bind不会调用函数,可以改变函数内部的this指向。 |
主要应用场景 | call经常用于继承。apply经常跟数组有关系,比如借助于数学对象实现数组的最值。bind不会调用函数,但是还行改变函数内部this的指向,比如改变定时器内部的this指向。 |
等一下( •́ .̫ •̀ ),我还有最后一句话:
我爱你,
他们说,
海最深邃,
干净而又透明 ,
我想 ,
是因为他们没有看到你的眼睛 ,
再见…