函数是 JavaScript 中的基本组件之一。一个函数是 JavaScript 过程 — 一组执行任务或计算值的语句。要使用一个函数,你必须将其定义在你希望调用它的作用域内。
每个 JavaScript 函数实际上都是一个 Function 对象。运行 (function(){}).constructor === Function // true 便可以得到这个结论。
Function fn(){
console.log(arguments) //获取所传入的参数(结果是一个伪列表,不具备列表的方法)箭头函数没有该属性
}
fn(1,2,3)
我们可以使用fn.call(xxx,1,2,3)传this和arguments
xxx会被自动转化为对象
fn()其实等价于fn.call(fn),js偷偷的帮你把this传了
//Lambda表达式的this
fn1=()=>{
console.log(this) //这里的this指向Window,且通过call反射也无法改变
}
fn1();//window
fn1.call(fn1,1,2,3) //window
functionfn2(){
console.log(this);
console.log(arguments)
}
fn2.call(fn2,1,5,2,3) //通过反射来改变this的指向,使其指向该函数
console.log(typeoffn2) //function
1.方法中的this
在对象方法中,this指的是此方法的“拥有者”。
varperson={
firstName:"Bill",
lastName:"Gates",
id:678,
fullName:function(){
returnthis.firstName+""+this.lastName;
}
};
console.log(person.fullName());//BillGates
2.单独的this
(1)在单独使用时,拥有者是全局对象,this指的是全局对象
在浏览器窗口中,全局对象是[object Window]:
varx=this;
console.log(x)//window
document.getElementById("demo").innerHTML=x;
(2)在严格模式中,如果单独使用,那么this指的是全局对象[object Window]:
"usestrict";
letx=this;
console.log(x)//Window
3.函数中的this(默认)
在js函数中,函数的拥有者默认绑定this.
因此,在函数中,this指的是全局对象[object Window]
Function myFunction(){
Return this;
}
console.log(myFunction());//window
4.函数中的this(严格模式)
js严格模式不允许默认绑定,因此,在函数中使用时,在严格模式下,this是未定义的undefined
"usestrict";
Function myFunction(){
Return this;
}
console.log(myFunction());//window
5.事件处理程序中的this
this指的是html元素,如下面例子中,this指的是button
<button onClick="this.style.display='none'">点击来删除我!</button>