英文:
How do I call a nested function from another file in typescript
问题
file1:
export func foo1 {
const foo2 { return something}
return foo1something
}
file2:
import { foo1 } from '../file1';
现在我怎么在这里访问foo2?
英文:
file1:
export func foo1 {
const foo2 { return something}
return foo1something
}
I just want to test this foo2 individual function in my test file:
file2:
import { foo1 } from '../file1';
Now how do I access foo2 here?
答案1
得分: 1
Your Import looks fine and the problems does not relate to "different files" or the "import".
let
and const
or nested functions
are block-scoped
, so they cannot be accessed outside of the original function. They are only available in the nested function (the block-scope
).
You can call the inner function inside the outer function itself.
export function foo() {
console.log('foo');
function bar() {
return bar
;
}
return bar()
}
console.log(foo());
result:
foo
bar
You can declare an object or class with nested functions or methods as properties and call it from the "outside":
File1:
export const someObject = {
foo: () => { console.log('foo') },
bar: () => { console.log('bar') }
}
File2:
import { someObject } from "./File1";
someObject.foo();
someObject.bar();
result:
foo
bar
英文:
Your Import looks fine and the problems does not relate to "different files" or the "import".
let
and const
or nested functions
are block-scoped
so they cannot be accessed outside of the original function.
they are only available in the nested function (the block-scope
).
You can call the inner function inside the oute function itself.
export function foo() {
console.log('foo');
function bar() {
return `bar`;
}
return bar()
}
console.log(foo());
result:
foo
bar
You can declare a object or class with nested functions or methods as properties and call it from the "outside":
File1:
export const someObject = {
foo: () => { console.log('foo') },
bar: () => { console.log('bar') }
}
File2:
import { someObject } from "./File1";
someObject.foo();
someObject.bar();
result:
foo
bar
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论