this指向的几种情况:
window
函数直接执行,函数名+括号 (非箭头函数)
匿名函数自执行
定时器直接调用
箭头函数暴露在全局
事件触发的元素
事件函数(不能是箭头函数)被触发的时候,事件函数内的this,指向事件元素
实例
new了之后就指向实例(默认return 是 this),return上方this指向构造函数的实例
构造函数的return 默认是 this ,如果写了一个,return 一个简单类型 ,那return的还是 this
如果写了一个,return 一个引用类型 ,那return的就是那个引用类型。
undefined
严格模式
'use strict'
声明变量必须使用var或let
arguments是不和形参相映射的
this指向一般是 undefined
对象的this
就是方法名.前面的对象(前提:不被定时器直接调用)
箭头函数 (文章末尾,简单介绍箭头函数)
this指向箭头函数的父级,只看定义时父级的域(比如,箭头函数在全局下,this指向window)
arguments[0]() 调用,this指向Arguments 对象
function fn(){ console.log(this); } let main = { fn:function(fn){ fn();//Window =》 单纯调用fn(),this指向Window arguments[0]()//Arguments 对象 =》用 arguments[0]() 调用,this指向Arguments 对象 } }main.fn(fn);
例子1:
1 function Person(name,age) {
2 this.name = name;//
3 this.age = age;
4 }
5 Person.prototype.say = function () {
6 console.log("我叫:"+this.name+",今年"+this.age+"岁")
7 };
8 let p = new Person("郭德纲",18);
9 p.say();//上面输出 :我叫:郭德纲,今年18岁
10
11
12 function fn(){
13 console.log(this);//Window
14 }
15 fn();
16
17 !function fn(){
18 console.log(this);//Window
19 }();
20
21 setTimeout(function(){
22 console.log(this);//Window
23 },1000);
24
25 // document.onclick = function(){
26 // console.log(this);//#document
27 // function fn(){
28 // console.log(this);//Window
29 // }
30 // fn();
31 // };
32
33 // document.onclick = function(){
34 // console.log(this);//#document
35 // }
36
37 // document.onclick = () => {
38 // console.log(this);//Window
39 // }
箭头函数
ES6新添加的函数表达式
let fn = function (){}
let fn = (a,b) => {
//执行语句
}
let fn = function (a){
return a+1;
}
箭头函数,不加{}就等同于return(只能有一行代码),加{}可以放多行代码。
let fn = (a) => a+1;
或者是
let fn = a => a+1;
注意:
如果没有参数,必须写括号
this指向老爹(当前箭头函数的上级)
例子1:
document.onclick = function () {
let fn = () =>{
console.log(this);//#document 箭头函数执行,this指向父级
};
fnn(fn);
};
function fnn(fn) {
console.log(this);//Window 函数名单纯调用(没有.点前面的主)this指向window
fn(this);
}
例子2:
document.onclick = function(){
(()=>{
console.log(this);//#document
})()
}
例子3:
let fn = a => a+1;
let fn = () => 1+1; //如果没有参数,必须写括号
console.log(fn(1));