this point of anonymous function in ES6/Typescript

Keywords: Javascript axios

Previously, it was thought that the call object was pointed to the global object when the function call was not set, but recently it was found that this of anonymous function was a little strange, and it was hard to be clear without an instance. Let's start with a piece of code from a graphql module case

import { Injectable, ProviderScope } from '@graphql-modules/di';
import { resolve } from 'path';
import axios from 'axios';
import { trackProvider } from '@safe-api/middleware';
import { RandomPhoto } from '../../types/unsplash';

interface RandomPhotoInput {
  query: string;
  orientation: 'landscape' | 'portrait' | 'squarish';
}

@Injectable({
  scope: ProviderScope.Application,
})
export class UnsplashApi {
  baseURL = 'https://api.unsplash.com/';

  async getRandomPhoto() {
    const trackedRandomPhoto = await trackProvider(
      async ({ query, orientation }: RandomPhotoInput) => {
        const response = await axios.get<RandomPhoto>('photos/random', {
          baseURL: this.baseURL,
          headers: {
            Authorization:
              'Client-ID 4d048cfb4383b407eff92e4a2a5ec36c0a866be85e64caafa588c110efad350d',
          },
          params: {
            query,
            orientation,
          },
        });

        return response.data;
      },
      {
        provider: 'Unsplash',
        method: 'RandomPhoto',
        location: resolve(__dirname, '../logs/main'),
      }
    );

    try {
      return (await trackedRandomPhoto({
        query: 'portrait',
        orientation: 'squarish',
      })).urls.small;
    } catch (err) {
      console.error('Cannot retrieve random photo:', err);
      return null;
    }
  }
}

Executing the instance method getRandomPhoto of UnsplashApi class will execute await trackprovider (callback), which is an anonymous function. There are
baseURL: this.baseURL this here points to the UnsplashApi instance. If it is not a callback anonymous function, this points to the global

Then I designed the application of this phenomenon in proxy, an alarm

class A {
    showWaringMessage(property){
            console.log(`${property} is not exit`)
        }
    createProxy() {
        
        let handeler = {}
        handeler.get=(target, property, receiver) =>{
                        //console.log(this)
                       let result = Reflect.get(target, property, receiver)
                       if(!result){
                           this.showWaringMessage(property)
                       };
                       return result
                    }
        
        const proxy = new Proxy({},handeler
       
        );
        return proxy
    }
}


let aDemo = new A()
aDemo.createProxy().a

Posted by Nathaniel on Sun, 08 Dec 2019 11:10:27 -0800