[英]Extending (inherit) class (or object ) in Javascript
I'm working on a UI automation project where i want to extend one page object from another page object. 我正在一个UI自动化项目中,我想从另一个页面对象扩展一个页面对象。 I googled for the way to achieve this but couldn't find exactly what i am searching for. 我用谷歌搜索了实现这一目标的方法,但是找不到我正在寻找的东西。 Basically i have a code setup something like this. 基本上我有这样的代码设置。
BasePage.js BasePage.js
define([],
function () {
function BasePage(remote) {
this.remote = remote;
}
BasePage.prototype = {
constructor: BasePage,
// common methods to interact with page
commonMethodToIntreactWithPage : function{
return doSomething;
}
};
return BasePage;
});
LoginPage.js LoginPage.js
define([],
function () {
function LoginPage(remote) {
this.remote = remote;
}
LoginPage.prototype = {
constructor: BasePage,
// Login Page related Methods
loginPageRelatedMethod: function{
return doSomething;
}
};
return LoginPage;
});
I want to inherit the method of BasePage
in LoginPage
by just doing this: 我想通过这样做来继承LoginPage
中BasePage
的方法:
var loginPage = new LoginPage(remote);
loginPage.commonMethodToIntreactWithPage();
Just for information I'm using Intern.js
for testing. 仅供参考,我正在使用Intern.js
进行测试。
You need to define something like this. 您需要定义这样的内容。 The first row will create a new object with the properties and methods, which are in BasePage.prototype
and set the prototype reference to this, so every LoginPage
object will have those properties and objects. 第一行将创建一个具有属性和方法的新对象,这些属性和方法位于BasePage.prototype
并为此设置原型引用,因此每个LoginPage
对象将具有这些属性和对象。 After all I add all specific data which is related only to LoginPage
( loginPageRelatedMethod
). 毕竟,我添加了仅与LoginPage
( loginPageRelatedMethod
)有关的所有特定数据。 And also it is important to set the proper constructor
. 设置适当的constructor
也很重要。
LoginPage.prototype = Object.create(BasePage.prototype);
LoginPage.prototype.constructor = LoginPage;
LoginPage.prototype.loginPageRelatedMethod = function(){
return doSomething;
}
UPDATED 更新
function LoginPage(remote) {
BasePage.call(this, remote);
}
Example 例
function BasePage(remote) { this.remote = remote; } BasePage.prototype = { constructor: BasePage, commonMethodToIntreactWithPage : function() { return 'From Base Page'; } }; function LoginPage(remote) { BasePage.call(this, remote); } LoginPage.prototype = Object.create(BasePage.prototype); LoginPage.prototype.constructor = LoginPage; LoginPage.prototype.loginPageRelatedMethod = function () { return 'From Login Page'; } var loginPage = new LoginPage('Test'); console.log(loginPage.commonMethodToIntreactWithPage());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.