首页 > 解决方案 > 分组/嵌套获取函数

问题描述

我正在扩展(对不起,来自其他语言的错误名称,我是 JS 新手)Page对象,通过添加很多函数,例如firstLevelFunction1firstLevelFunction2. 我的目标是将这些函数分组,以便我可以像这样通过点访问它们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 框架。将功能分组到第二级是我的想法,以使文件更加清晰和结构化。

标签: javascriptwebdriver-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';
            }
        }   
    }
},

推荐阅读