函数在定义的时候不会影响它的this指向,只有在调用的时候选择不同的调用方式,才会决定你this指向何处。
在独立函数调用的时候,this指向window,在调用挂载在window的函数时,前面的window可以省略不写,
function foo() {
console.log(this);//此处this指向window
}
foo()
严格模式下,独立函数this的指向是undefined,不再是window
"use strict"
在对象调用方法时,this指向的是调用者
function fn() {
console.log(this); //此处的This指向obj
}
let obj = {
name: "靓仔",
}
obj.fo = fn;
obj.fo()//等价于
let obj = {
name: "靓仔",
foo() {
console.log(this);
}
}
obj.foo()
但是用一个变量给对象的方法赋值的时候
let obj = {
name: "靓仔",
foo() {
console.log(this);
}
}
let s = obj.foo //s是挂载在window上的变量,指向window
s() //等价于
function s() {
console.log(this);
}
构造函数里的this指向的就是事件本身
function stu(a) {
console.log(this); //指向stu {}
}
let s = new stu("靓仔") //stu
点击事件的this指向的时事件对象,就是触发这个点击事件的事件源
let btn = document.querySelector("#btn")
btn.onclick = function() {
console.log(this); //button
}
function fn() {
console.log(this);
}
let arr = [12, 3, 5, 6, 345, 765, 234, 1234, 123, 56, 567, 67, 567, 67, 67]
arr.forEach(function() { //foreach里面可以写两个参数,一个是遍历的数组,另一个是this的指向,写啥指啥
console.log(this); //全是fn
}, fn)
call,apply ,bind的使用改变this指向
function so(a, b, c, d) {
console.log(this);
console.log(a, b, c, d);
}
function father() {
console.log();
}
// so.call(father, "靓仔", 18, 180, "牛")//call方法传字符串变量
so.apply(father, ["靓仔", 18, 180, "牛"])//apply传一个数组
// var s = so.bind(father, "靓仔", 18, 180, "牛")//bind方法不会调用函数,会产生一个函数,然后再手动调用
// s()
箭头函数是没有this指向的,没有this就往父级找,如果父级也是箭头函数就继续往父级找,就形成作用域链,直到找到全局作用域
function req(u, c) {
let arr = ["靓仔", "头头", "是我"]
c(arr)
}
let obj = {
data: [],
newo: function() {
req("/login", name => name.map(element => _this.data.push(element)))
}
}
obj.newo()
console.log(obj.data);