Arrow function does not have its own this, arguments, super or new.target?

Arrow function does not have its own this, arguments, super or new.target?

Preface

Recently, when looking at the es6-promise code, I found a very interesting phenomenon (reject(1,2,3) does not correspond to the parameters of the method in catch), in order to verify this problem, I used the following code, but found a new problem:

new Promise((resolve,reject)=>{
    
    
    reject(1,2,3)
}).then((res)=>{
    
    

}).catch((val,val2,val3)=>{
    
    
	// reject(1,2,3)并不对应catch里面方法的参数
  	console.log(val);//1
    console.log(val2);//undefined
    console.log(val3);//undefined
    console.log(arguments);//ReferenceError: arguments is not defined
})

After encountering this error, I began to look through the JavaScript arrow functions that I recorded before , but found that there was only a description of this (The number of arrow rows will promote this in the method body to the upper level of the scope), and this description feels very obscure to me. Finally, I found the answer in the arrow function in MDN , and the description (Arrow functions do not have their own this, arguments, super or new.target) Personally feel a little easier to understand.
When I first saw the description in MDN, I was curious.Arrow functions do not have their own (this, arguments, super or new.target), but can use external functions (this, arguments, super or new.target) still isThe arrow function does not have its own this, (arguments, super or new.target), and can only use the this of the external function, but cannot use arguments, super or new.target in the arrow function

verification

;(function(){
    
    
    ;(()=>{
    
    
        console.log(this);//Window
        console.log(arguments);//Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
        console.log(new.target);//undefined
    })()
})(1,2,3);

///
class Animal{
    
    
    constructor(){
    
    
        console.log('xxxxxxxx');
    }
}
class Person extends Animal{
    
    
    constructor(){
    
    
        ;(()=>{
    
    
            super();//正常
            console.log(this);//Person {}  new出来的对象
            console.log(arguments);//Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
            console.log(new.target);//function Person(){ xxxx } 指向此函数的引用
        })()
    }
}
new Person();

in conclusion

After the above code, it is concluded:The arrow function does not have its own (this, arguments, super or new.target), but the nearest external function (this, arguments, super or new.target) can be used

Guess you like

Origin blog.csdn.net/qq_35508835/article/details/108179667