How to access nested function in Javascript from another function?

匆匆过客 提交于 2021-01-28 11:11:43

问题


In case I have

import axios from "axios";

function model() {
  function getAll() {
    return axios
      .get("http://localhost:3000/teams")
      .then(response => response.data);
  }
}

export default model;

How can I access getAll() method from another component ?

I tried importing model and then referring it to getAll - model.getAll(), but it complains that the method is undefined.

I tried referring to Calling a Function defined inside another function in Javascript , but could not find the solution.

Is this even the correct approach?


回答1:


You can't access getAll from anywhere except inside model. Maybe you meant to create an object?

var model = {
    getAll: function () { ... }
}

model.getAll();



回答2:


You could always instantiate the function

function model() {
  this.getAll = () => {
    console.log("hello world");
  };
}

const myFunc = new model();

myFunc.getAll() // console.log('hello world')


来源:https://stackoverflow.com/questions/52931016/how-to-access-nested-function-in-javascript-from-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!