gpt4 book ai didi

javascript - 如何正确访问模块内的类属性和函数

转载 作者:行者123 更新时间:2023-12-02 21:46:10 25 4
gpt4 key购买 nike

我正在使用对象文字在 ES6 模块中编写类,并且我想在函数中设置对象属性。现在我知道模块默认以严格模式执行,这使得 this 的使用安全或至少更安全,但我不确定 foo() 是否修改了我的对象正在访问“父”脚本文件或仅存在于 Controller.mjs 中的本地对象。两个函数调用的效果相同吗?

//Controller.mjs
const Controller = {
someAttr1: [],
someAttr2: true,

foo: function () {
this.someAttr1.push("some value");
Controller.someAttr1.push("some value");
}
};

//export Controller's interface...

//SomeOtherFile.mjs
import { Controller } from 'Controller.mjs'

Controller.foo();

最佳答案

the object I'm accessing in the 'parent' script file or just the local object existing only in Controller.mjs

您的代码中只有一个对象。 import 声明实际上什么也不做,只是为导入的模块中的 const Controller 变量创建一个别名。没有第二个对象被实例化。

一般来说,要使用 thisController 来引用对象,请参阅 Javascript: Object Literal reference in own key's function instead of 'this' 。代码是否跨模块分布并不重要。

关于javascript - 如何正确访问模块内的类属性和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com