js中的this指向
方法是谁调用的,那么在方法中this就指向谁(.前面是谁, this就是谁)
let obj = {
fn: function () {
console.log(this);//obj
}
};
obj.fn();
如果没有调用 this始终指向window(定时器中this指向window
function fn() {
console.log(this);//window
}
fn();
setTimeout(()=>{
console.log(this)//window
},100)
构造函数中的this, 指向实例本身
function Fn(name){
this.name = name;
this.age = 18;
console.log("Fn中的this==>",this); //Fn {name: ' ^.^ ', age: 18}
}
Fn.prototype.sayName = function(){
console.log("sayName中的this==>",this) // Fn {name: ' ^.^ ', age: 18}
}
let fn = new Fn(" ^.^ ");
改变this指向call、apply、bind
call、apply、bind都是改变this指向的方法,可以传参
let obj = {
name: "许宣",
birth: 1990,
age: function(arg1, arg2){
console.log(this.name);//许宣
console.log(arg1, arg2);//"参数1","参数2"
}
}
obj.age("参数1","参数2");
call -- call(新的this指向,"参数1","参数2")
let obj = {
name: "许宣",
birth: 1990,
age: function(arg1, arg2){
console.log(this.name);//小白
console.log(arg1, arg2); //"参数3","参数4"
}
}
//obj.age("参数1","参数2");
let obj2 = {
name: "小白",
birth: 2000,
};
obj.age.call(obj2,"参数3","参数4")
apply -- apply(新的this指向,["参数1","参数2"])
let obj = {
name: "许宣",
birth: 1990,
age: function(arg1, arg2){
console.log(this.name);//小青
console.log(arg1, arg2); //"参数5","参数6"
}
}
//obj.age("参数1","参数2");
let obj2 = {
name: "小青",
birth: 2000,
};
obj.age.apply(obj2,["参数5","参数6"])
bind -- bind(新的this指向)( ) === let changeThisAge = obj.age.bind(obj2);
let obj = {
name: "许宣",
birth: 1990,
age: function(arg1, arg2){
console.log(this.name);//许仙
console.log(arg1, arg2);//"参数7","参数8"
}
}
obj.age("参数1","参数2");
let obj2 = {
name: "许仙",
birth: 2000,
};
//obj.age.bind(obj2)("参数7","参数8");
//let changeThisAge = obj.age.bind(obj2);
//changeThisAge("参数7","参数8")
总结:
call和apply和bind都是改变this指向的方法,call和apply直接调用。call传的参数用逗号分割;applay传递的是一个数组。bind不会直接调用,可以用 bind( )( )调用;--- bind本身不回去执行要被改变this指向的这个方法,而是返回一个已经被改变了this指向的新方法。所以也可以使
let changeThisAge = obj.age.bind(obj2);
箭头函数中的this指向
1.箭头函数的出现就是为了解决ES5中this指向混乱的问题
2.箭头函数没有自己的this,它的this来自父级上下文,并且永远指向父级上下文
3.箭头函数的this不会在调用的时候被改变, 因为箭头函数在声明的时候它的this就已经被永久的确定了
箭头函数的this,指向父级上下文
var a = 100;
let obj = {
a: 200,
fn: function () {
console.log(this);//obj
console.log(this.a);//obj.a = 200;
},
fn2: () => {
console.log(this);//window
console.log(this.a);//window.a = 100
}
}
obj.fn();
obj.fn2();
箭头函数与普通函数区别
箭头函数的this,始终指向父级上下文
箭头函数是匿名函数,不能作为构造函数,不能使用new
let Person = () => {
this.name = name;
this.age = 20;
}
let person = new Person();
//Uncaught TypeError: Person is not a constructor Person不是一个构造函数
箭头函数没有原型属性
箭头函数内没有arguments,可以用展开运算符...解决
let fn = (...args)=>{ //使用展开运算符接受参数集合
// console.log(arguments);// arguments is not defined
console.log(args); //是一个数组
}
箭头函数不能通过call()\apply()\bind()方法直接修改它的this指向 但是,可以正常传参
普通函数的arguments和类数组转换成数组
arguments(参数集合 == 伪数组。有长度有索引(下标),可以用for循环遍历,但没有数组push等方法。
Array.from(arguments);
Array.prototype.slice.call(arguments);
let arr = []
for (let i = 0; i < arguments.length; i++) {
arr.push(arguments[i])
}