this 的指向的理解
this 可以分为全局和局部环境来细分
全局环境中 ===>this指向 window
1、this表示当前的对象 this 的指向是根据上下文来决定的 默认指向的是window对象,可以省略不写
2、定时器中的this指向的是window
3、箭头函数中的this指向是父级作用域,可以说是上下文
- =>指向它的父级作用域,而不是调用它对象 箭头函没有自己的this
- 即时调用call/apply/bind也无法改变箭头函数的this
- 箭头函数本身没有名字
- 箭头函数不能new,会报错
- 箭头函数没有arguments,在箭头函数内访问这个变量访问的是外部执行环境的arguments
- 箭头函数没有super或new.target
- 箭头函数没有prototype原型
- 箭头函数中 原型链上的this指向的是window=>原型链上的箭头函数,定义它的时候,这个箭头函数的父级作用域是window
- 箭头函数表达式更适用于那些本来需要匿名函数的地方,并且他们不能用作构造函数
this 可以分为全局和局部环境来细分。
全局环境中 ===>this指向 window
局部环境中:
1、全局作用域中的this指向的 是 window
function func(){
console.log(this) ;//this指向的还是window对象
}
func()
*2、对象环境中=====对象函数调用 那个对象调用this就指向那个对象*
**3、构造函数环境中=======构造函数中的一级函数,this指向通过构造函数new出来的实例**
var Person = function () {
this.name = 'linlif'
this.fn = function () {
console.log('fn', this) // {name: "linlif", fn: ƒ}
}
}
var person = new Person()
person.fn()
4、构造函数中的二级(及以上)函数,this指向的是window
var Person = function () {
this.name = 'linlif'
this.fn = function () {
console.log('fn', this) // {name: "linlif", fn: ƒ}
var f2 = function () {
console.log('f2', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
var f3 = function () {
console.log('f3', this) // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
}
f3()
}
f2()
}
}
var person = new Person()
person.fn()
从上面的例子,我们可以总结出,构造函数中,嵌套超过一级及以上的函数,this指向的都是window
5、使用call(可以传参)或apply(以数组的方式传参)改变this的指向 bind(不能调用函数)
(1)自执行函数中的this永远是undefined
例如:
var obj = {
fn:(function() {
//this --> undefined
return function () {
//this -->obj
}
})(0)
};
obj.fn()
(2)方法执行,看方法前面是否有‘.’,有的话,‘.’前面是谁this就是谁,没有的话this就是undefined
例如:
var obj = function() {
fn:fn
}
function(){
fn()//undefined
}
obj.fn //this --> obj
6、严格模式下 ‘use strict’**
(1)自执行函数中的this永远是undefined
例如:
var obj = {
fn:(function() {
//this --> undefined
return function () {
//this -->obj
}
})(0)
};
obj.fn()
(2)方法执行,看方法前面是否有‘.’,有的话,‘.’前面是谁this就是谁,没有的话this就是undefined
例如:
var obj = function() {
fn:fn
}
function(){
fn()//undefined
}
obj.fn //this --> obj
这时候我们发现严格模式下的this相对于非严格模式下的this主要区别在于: 相对于js代码中没有执行主体的情况下,非严格模式下默认都是window;但是在严格模式下,没有写就是没有执行主体,this指向的是undefined
7、闭包 this默认指向window
五星加分项
1.用于区分全局变量和局部变量 ,需要使用 this
2.返回函数当前的对象,
3.将当前的对象传递到下一个函数
each:function(callback,args){
return jQuery.each(this,callback,args)
}
后文有待加载 请耐心等待