首页 > 其他分享 >cocos creator教程:框架 - 封装

cocos creator教程:框架 - 封装

时间:2023-01-07 23:36:03浏览次数:38  
标签:... cocos 封装 creator tool namespace ts export test

【muzzik 教程】:框架 - 封装

遇到的问题

  • 部分接口/属性不想暴露给外部
  • 外部引用方式
  • 框架加载方式

部分接口/属性不想暴露给外部

export class private_test {
	test_b = false;
	func(): void {...}
}

如果我们想重载 test_b 和 func 该怎么做呢?按照下方编写操作即可

interface test_safe_prototype extends test {
	readonly test_b: boolean;
	func: never;
}

export type test = Omit<typeof private_test, "prototype"> & {
	prototype: Omit<test_safe_prototype, "func">;;
	new (...args: ConstructorParameters<typeof private_test>): typeof test["prototype"];
};
export const test = private_test as any as test;

这样外部使用 new test() 时 test_b 就变成只读属性了,func 函数则直接调用报错,而我们可以在框架内部代码使用 private_test

外部引用方式

我们的使用方式不会影响代码集成后的对象类型;比如 namespace 集成后还是 namespace,而不是一个 Object,这点很重要

tool_a.ts

// 内部使用的类型、枚举等
export namespace _tool_a {...}

// 类型
class tool_a {...}

// 外部使用的类型、枚举等
export namespace tool_a_ {...}

export default tool_a;

tool_b.ts

// 内部使用的类型、枚举等
export namespace _tool_b {...}

// 类型
export class tool_b {...}

// 外部使用的类型、枚举等
export namespace tool_b_ {...}

export default tool_b;

tool_export.ts(导出脚本)

export { default as a, tool_a_ as a_} from "./tool_a.ts";
export { default as b, tool_b_ as b_ } from "./tool_b.ts";

tool.ts(集成脚本)

import * as tool from "./tool_export";

export default tool;

外部使用

let a = tool.a.xxx;
let b: tool.a_.xxx;

注意事项:如果内部互相引用不要直接导入 tool.ts 脚本,会造成循环引用,内部引用时只需要引用指定脚本

框架加载方式

// ...

标签:...,cocos,封装,creator,tool,namespace,ts,export,test
From: https://www.cnblogs.com/muzzik/p/17033835.html

相关文章