使用 __proto__ 在 Protractor 中扩展基页对象

Extending a base page object in Protractor with __proto__

下面的代码工作得很好......但是使用 __proto__ 似乎被认为是有争议的。在 Protractor/Nodejs 的范围内是这样吗?如果是这样,我还能如何完成同样的事情?

给定一个 basePage:

var BasePage = function() {
  this.to = function() {
    browser.get(this.url);
  };
};
module.exports = new BasePage;

还有一个可以扩展 BasePage 的页面:

var basePage = require('../pages/basePage.js');

var MyPage = function() {
  this.__proto__ = basePage; // extend basePage...
  this.url = 'http://myPage.com';
};
module.exports = new MyPage;

当测试调用时:

var myPage = require('../pages/myPage.js');

it('should go to page', function() {
  myPage.to();
}; 

然后赢?

在下面的代码片段中,您可以尝试涉及原型继承的不同想法。我个人的看法是,在 subclass 构造函数中调用 base class 构造函数更为传统。这样你就可以在任何浏览器和 Node 中使用你的代码。

var baseDiv = document.getElementById("base");
var subDiv = document.getElementById("sub");

var BaseClass = function BaseClassConstructor(div) {
    this.div  = div;
};

BaseClass.prototype.text = "I'm the base class!";

BaseClass.prototype.to = function BaseClassTo() {
  this.div.innerHTML = this.text;
}

// This SubClass calls the base class constructor on its "this" context.
var SubClass = function SubClassConstructor(div) {
  BaseClass.call(this, div);
};

// The prototype is then constructed by cloning the base class prototype.
SubClass.prototype = Object.create(BaseClass.prototype);

SubClass.prototype.text = "I'm the sub class!";

var b = new BaseClass(baseDiv);
var s = new SubClass(subDiv);

s.to();
b.to();
<div id="base"></div>
<div id="sub"></div>

but it would seem using__proto__ is considered controversial.

Yes.

Is this true in the confines of Protractor/Nodejs?

是的,即使至少在已知环境中你可以确定它是有效的。

And if so, how else could I accomplish the same thing?

没有理由像您那样在构造函数中设置 __proto__。这就是 .prototype 属性 的用途!这将完全像您的代码一样工作:

var basePage = require('../pages/basePage.js');

var MyPage = function() {
  this.url = 'http://myPage.com';
};
MyPage.prototype = basePage; // extend basePage...
module.exports = new MyPage;

但是,导出构造函数的实例有点奇怪。如果您的目标是创建单例对象,don't use constructors and new. If your goal is to create a "class", you should export the constructor function (and do inheritance a bit different).