`this` не определено внутри объекта - PullRequest
0 голосов
/ 15 апреля 2020

При Nodejs я вызываю функцию с именем customFunction, которая является мутацией из резольвера GrpahQL. У меня нет доступа к this.

import { Mutation } from './mutation/Mutation'
export default {
  Query,
  Mutation,
}

затем в Mutation.ts

import { customFunctionMutation } from './customFunctionMutation'
export const Mutation = {
  customFunction: customFunctionMutation.customFunction,
}

, затем в customFunctionMutation.ts

export const customFunctionMutation = {
  test() {
    console.log('test called')
  },
  async customFunction(parent: any, args: any, ctx: any, info: any) {
    console.log('customFunction init')
    console.log('this', this)
    this.test()
    console.log('customFunction end')
  },
}

это undefined, и я не могу вызвать функцию test() который находится в том же объекте

enter image description here

Ответы [ 2 ]

2 голосов
/ 15 апреля 2020

Вы отделили метод от объекта, который имеет метод test, когда сделали это:

import { customFunction } from './customFunction'

Итак, когда вы попытаетесь вызвать customFunction(), он не будет связан с объектом он объявлен внутри и, следовательно, не может ссылаться на this.test(), потому что this будет undefined.

К вашему сведению, присвоение экспорту того же имени, а свойство при экспорте безнадежно сбивает с толку ваши клиенты. Пожалуйста, не делайте этого.


Я бы предложил исправить это, сделав ваш модуль независимым от того, как он вызывался, изменив его, чтобы он больше не использовал this:

const moduleObj = {
  test() {
    console.log('test called')
  },
  async customFunction(parent: any, args: any, ctx: any, info: any) {
    console.log('customFunction init')
    console.log('this', this)
    moduleObj.test()
    console.log('customFunction end')
  },
}

export default moduleObj;

Затем вы можете использовать:

import { customFunction } from './customFunction'

И затем вы можете позвонить:

customFunction()

, и он сможет нормально функционировать при вызове.

1 голос
/ 15 апреля 2020

Вероятно, один из них может работать:

import { customFunction } from './customFunction'
export const Mutation = {
  customFunction: customFunction.customFunction.bind(customFunction),
}

или

import { customFunction } from './customFunction'
export const Mutation = customFunction

или

import { customFunction } from './customFunction'
export const Mutation = {
  customFunction: function functionName(...parameters) { return customFunction.customFunction(...parameters); },
}
...