如何向 JavaScript 中的对象添加可以访问其变量的函数

发布于 2024-12-06 13:23:15 字数 513 浏览 1 评论 0原文

我正在尝试做一些 javascript 测试驱动开发,并且想用模拟的 dao 替换 dao。

假设我有一个对象 myObject,它有一个私有 var dao,我想为其创建一个 setter:

var dao = new RealDao();

function funcUsesDao() {
    dao.doStuff();
}

然后在另一个文件中,我有一个该对象的实例的句柄,并且想要添加一个 setter,以便我可以执行以下操作:

var mockDao = {function doStuff() { /*mock code */}};
myObject.setDao(mockDao);
myObject.funcUsesDao(); should use mock dao

环境细节是这是node.js,我拥有句柄的对象是通过执行 var myObject = require('../myObject'); 获得的

I am trying to do some javascript test driven development, and would like to replace a dao with a mock one.

Lets say I have an object myObject that has a private var dao that I would like to create a setter for:

var dao = new RealDao();

function funcUsesDao() {
    dao.doStuff();
}

Then in another file I have a handle to an instance of this object and want to add a setter so I can do the following:

var mockDao = {function doStuff() { /*mock code */}};
myObject.setDao(mockDao);
myObject.funcUsesDao(); should use mock dao

Environment specifics are this is node.js and the object I have a handle to is obtained by doing var myObject = require('../myObject');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过潦 2024-12-13 13:23:15

您可以使用该类的构造函数,将 dao 设置为 RealDao,然后在 setDao 中将该 dao 设置为新的 dao。或者,在构造函数中放置对 dao 的引用,并在 null 上将其分配给新的 RealDao()。 (至少,这是我对人们通常如何通过构造函数分配新接口进行测试的理解)

//something like this
function Dao(interface){
  this.dao = interface || new RealDao();
}

否则,您上面列出的内容是准确的。您只需提供代码中所示的 setDao 方法即可。

You would use a constructor for the class, setting the dao to RealDao and then in the setDao you would set that dao to the new dao. Alternately in the constructor you would put a reference to dao, and on null, assign it to a new RealDao(). (at least, that's been my understanding of how people generally assign new interfaces for testing .. via the constructor)

//something like this
function Dao(interface){
  this.dao = interface || new RealDao();
}

Otherwise, what you listed above is accurate. you just have to provide the setDao method as you indicated in your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文