部分this指向

137 阅读2分钟
  • 匿名函数,定时器,计时器里面的this都是指向window
  • 普通函数中的this指向window,属于默认绑定。构造函数中的this指向实例化的对象,属于显示绑定
  •  this是在函数执行的过程中确定指向,谁调用这个函数this就指向谁,与在创建时和哪里创建是没有关系
  • 箭头函数默认本身不会有this而是默认绑定外层的this

    var number = 5;
    var obj = {
        number: 3,
        fn1: (function () {
            var number;
            this.number *= 2;
            number = number * 2;
            number = 3;
            return function () {
                var num = this.number;
                this.number *= 2;
                number *= 3;
            }
        })()
    }
    var fn1 = obj.fn1;
    fn1.call(null); // 这个里面的this 全都是 window
    obj.fn1(); // 这个里面 匿名函数中的this 是window但是return的函数中是this是调用者 obj
    console.log(window.number);
var f = function () {
    console.log(this.a)
};
var a = 1;
var obj = {
    a: 2,
    f: f
}
f() // 1 this 指向的是window 也就是window.a
obj.f() // 2 this指向的是obj 也就是obj.a

var add = function (x, y) {
  return x * this.m + y * this.n;
}

var obj = {
  m: 1,
  n: 2
};

var newAdd = add.bind(obj, 5);// bind 绑定了 this 为 obj 此时 this.m = 2 this.n = 2 并且传递了一个参数 x = 5
newAdd(4) //13 这是传递了一个参数 y = 4;  13 = 5 * 1 + 4 * 2

//普通函数
var obj = {
    a: 1,
    get: function() {
        console.log(this) // obj 函数的调用者
    }
}
// 箭头函数
var obj = {
    a: 1,
    get:() => {
        console.log(this)
    }
}
obj.get()// window 箭头函数 this 值默认和外层的this 值一样
obj.get.call(obj); // window call 不能改变箭头函数的this指向

var obj = {
	a: 1,
	get:() => {
		console.log(this)
	},
	b: {
		getThis: ()=> {
			console.log(this);
		}
	}
}
obj.b.getThis() // window 多层对象嵌套箭头函数的this是最外层的this一样

apply、call、bind : apply和call是立即调用,都是为了改变某个函数内部的this指向。

apply的第二个参数是数组或者是一个类数组,call的第二个参数及是逐个传递的 bind是返回对应函数可以给这个函数指定this指向 

可以使用Array.prototype.slice.call() 把类数组转化为标准数组 

可以使用Object.prototype.toString.call()来判断数据类型