js中的this指向
1.方法中 谁调用,this就指向谁 (.前面是谁,this就指向谁)
2.如果没有人调用的时候this默认的指向window
3.构造函数中的this,指向通过这个构造函数创建出来的实例本身
4.强制改变this指向 call apply bind
箭头函数中的this指向
箭头函数的出现就是为了解决ES5中this指向混乱的问题
箭头函数的this指向来自父级上下文, 箭头函数没有自己的this
箭头函数的this不会在调用的时候被改变, 在箭头函数声明的时候他的this就已经被永久的确定
箭头函数与普通函数区别
箭头函数是匿名函数 箭头函数不能作为构造函数使用 不能使用new
{
function Fn(name){
this.name = name;
this.age = 6;
console.log("Fn中的this==>",this); //new Fn()
}
let fn = new Fn("哈");
let Fn = ()=>{
this.name = name;
this.age = 6;
}
let fn = new Fn(); //Fn is not a constructor
}
箭头函数的this,始终指向父级上下文
{
let obj = {
a: 100,
fn: function(){
console.log(this);//obj
},
fn2: ()=>{
console.log("fn2====>",this);//window
}
};
obj.fn();
obj.fn2();
}
箭头函数不能通过call apply bind改变this指向,但是可以通过这些方法传递参数
{
let obj = {
name: "obj",
birth: 1990,
year: 2021,
age: (arg1, arg2)=>{
console.log(this);//window
console.log(arg1, arg2);//obj2
console.log("my age =", this.year - this.birth)
}
}
let obj2 = {
name: "obj2",
birth: 2000,
year: 2020,
};
obj.age.call(obj2,"参数1","参数2")
}
箭头函数没有原型属性
{
// function fn(){}
let fn = ()=>{};
console.dir(fn);
}
箭头函数没有arguments属性,可以用...展开运算符来接收所有的参数集合
{
function fn(){
console.log(arguments);
// fn.caller 谁在调用当前的方法 会返回这个方法本身
// arguments.callee ===> 当前这个方法本身;
// arguments 参数集合 是一个类数组 不能调用数组的方法
}
fn(1,2,3)
let fn = (...args)=>{ //使用展开运算符接受参数集合
// console.log(arguments);// arguments is not defined
console.log(args); //是一个数组
}
fn(1,2,3)
}
普通函数的arguments和类数组转换成数组
Array.prototype.slice = function (){
console.log(this); //this = arguments
let newArr = [];
for (let i=0;i<this.length;i++){
newArr.push(this[i])
}
return newArr
}
let arr = [1,2,34];
let arr2 = arr.slice();
arr2[0] = 1000;
console.log(arr,arr2);