javascript - 分组/嵌套获取函数
问题描述
我正在扩展(对不起,来自其他语言的错误名称,我是 JS 新手)Page
对象,通过添加很多函数,例如firstLevelFunction1
和firstLevelFunction2
. 我的目标是将这些函数分组,以便我可以像这样通过点访问它们firstLevelGroup.secondLevelFunction1
:我创建firstLevelGroup
的方式与firstLevelFunction
. 函数testLevels
只是为了验证不同级别的行为,当我调用它时,输出是:
一级函数
1 一级函数
2 { get: [Function: get] }
{ get: [Function: get] }
虽然我期望:
一级功能
1 一级功能
2 二级功能1
二级功能2
我的代码:
let Page = require('./../page')
let JsTestingPage = Object.create(Page, {
firstLevelFunction1: {get: function () { return 'first level function1' }},
firstLevelFunction2: {get: function () { return 'first level function2' }},
firstLevelGroup: { get: function () {
return {
secondLevelFunction1: {
get: function () {
return 'second level function1'
}
},
secondLevelFunction2: {
get: function () {
return 'second level function2'
}
}
}
}
},
testLevels: {value: function () {
console.log(this.firstLevelFunction1)
console.log(this.firstLevelFunction2)
console.log(this.firstLevelGroup.secondLevelFunction1)
console.log(this.firstLevelGroup.secondLevelFunction2)
}}
})
module.exports = JsTestingPage
我也尝试了其他版本,但没有成功。上面的至少不会返回错误。
请告诉我如何对功能进行分组。另外,请随意说对函数进行分组是没有意义的 :)
顺便说一句,这种结构(第一级)或多或少来自 webdriver.io 框架。将功能分组到第二级是我的想法,以使文件更加清晰和结构化。
解决方案
发生这种情况是因为您正在返回一个对象初始化程序,其中get
成为一个普通的方法名称,它不会为内部对象创建一个 getter。要解决此问题,请将返回的对象包装在其中Object.create(null, {...})
(或使用更有意义的原型,如果提供),您将得到您所期望的。
let JsTestingPage = Object.create(null, {
firstLevelFunction1: {
get: function() {
return 'first level function1';
}
},
firstLevelFunction2: {
get: function() {
return 'first level function2';
}
},
firstLevelGroup: {
get: function() {
return Object.create(null, {
secondLevelFunction1: {
get: function() {
return 'second level function1';
}
},
secondLevelFunction2: {
get: function() {
return 'second level function2';
}
}
});
}
},
testLevels: {
value: function() {
console.log(this.firstLevelFunction1);
console.log(this.firstLevelFunction2);
console.log(this.firstLevelGroup.secondLevelFunction1);
console.log(this.firstLevelGroup.secondLevelFunction2);
}
}
});
JsTestingPage.testLevels();
或者在对象初始化器中创建 getter:
firstLevelGroup: {
get: function() {
return {
get secondLevelFunction1 () {
return 'second level function1';
},
get secondLevelFunction2 () {
return 'second level function2';
}
}
}
},
推荐阅读
- html - 如何修复我的圆形进度条以在 safari 上工作?
- javascript - 如何在悬停或单击时向上打开表单?
- html - MapTimeBoston 传单教程 RatMap 对象
- json - JPA @OneToMany 注释正在循环
- android - 将事件添加到日历显示错误的时间,但保存时时间是正确的
- python - 使用 sklearn.datasets.load_files 导入的数据集的标签
- javascript - 如何使用 ReactJS 调用函数内部的方法(单击 a href 注销)
- beautifulsoup - 对 bs4 imorting 方法及其对属性的影响感到困惑
- c# - CosmosDB 中的小写文档
- snakemake - 输入和输出中的通配符不起作用