函数中的this的指向
普通函数
//普通函数
function f1() {
console.log(this);
}
f1();//window
定时器中的this
setInterval(function () {
console.log(this);
},1000);//window
构造函数
//构造函数
function Person() {
console.log(this);//实例对象
对象的方法
//对象的方法
this.sayHi=function () {
console.log(this);//实例对象
};
}
原型中的方法
//原型中的方法
Person.prototype.eat=function () {
console.log(this);
};
var per=new Person();
console.log(per);
per.sayHi();//实例对象
per.eat();
总结:
- 普通函数中的this是谁?—–window
- 对象.方法中的this是谁?—-当前的实例对象
- 定时器方法中的this是谁?—-window
- 构造函数中的this是谁?—–实例对象
严格模式:
"use strict";//严格模式
function f1() {
console.log(this);//window
}
f1();//undefined
window.f1();//window
我们可以看出在严格模式下 我们对代码的的调用必须严格的写出被调用的函数的对象,不可以有省略或者说简写