js中this指向通常是谁调用就指向谁,也就是·前边是谁 就指向谁,如果没有人调用就是window调用,就指向window
let obj = { f: function () { console.log(this);//obj } }; obj.f(); function fn() { console.log(this);//window } fn(); setTimeout(()=>{ console.log(this)//window
js构造函数中的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、bind、apply。
call方法改变this指向,可以传参,参数用逗号隔开。
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方法修改this指向,也可以传参,参数是一个数组。
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方法修改this指向,不会立即执行,而是返回一个this指向被修改过的新方法,需要调用才会执行,传参方式和call方法一样。
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")()
箭头函数中的this指向
1.箭头函数的出现就是为了解决ES5中this指向混乱的问题
2.箭头函数没有自己的this,它的this来自父级上下文,并且永远指向父级上下文
3.箭头函数的this不会在调用的时候被改变, 因为箭头函数在声明的时候它的this就已经被永久的确定了,所以也不能被bind,apply,call方法修改。
箭头函数与普通函数区别
箭头函数的this,始终指向父级上下文
箭头函数是匿名函数,不能作为构造函数,不能使用new
箭头函数没有原型属性
let Person = () => {
this.name = name;
this.age = 20;
}
let person = new Person();
//Uncaught TypeError: Person is not a constructor Person不是一个构造函数
箭头函数内没有arguments,可以用展开运算符...arg解决
let fn = (...args)=>{ //使用展开运算符接受参数集合
// console.log(arguments);// arguments is not defined
console.log(args); //是一个数组
}
arguments类数组转化成数组的方法。
两种方法原理是一样的,都是创建一个空数组,把类数组的参数一个一个追加到空数组里
Array.prototype.slice.call(arguments);
let arr = []
for (let i = 0; i < arguments.length; i++) {
arr.push(arguments[i])
}