![](/img/trans.png)
[英]How to create new JavaScript class based on an existing class and extend it
[英]JavaScript : Create new object of a custom class based on an existing one (adding methods to it)
我使用iOS UI自动化框架来确保我的iPhone应用程序顺利运行。
使用此框架的每个人都会告诉您,它很棒,但是缺乏很多结构。
因此,我必须处理UIAWindow实例,它们代表我的应用程序的不同屏幕。 为了更加面向对象,我希望每个屏幕都有一个特定的类,因此我可以添加特定的方法,例如
myScreen1.tapDoneButton();
var total = myScreen2.getNumberOfElements();
目前,我可以通过将UIAWindow实例传递给将添加适当方法的函数来实现此目的,例如:
function makeMainScreen(actualScreen)
{
actualScreen.constructor.prototype.getAddButton = function() {
return this.buttons()["add button"];
};
actualScreen.constructor.prototype.tapAddButton = function() {
this.getAddButton().tap();
};
// Add any desired method...
return actualScreen;
}
它工作正常,我像这样使用它:
var mainScreen = makeMainScreen(app.mainWindow());
mainScreen.tapAddButton();
但这似乎还不够面向对象,我想使用new和this关键字创建真实的对象,所以我会有一个这样的声明:
function MainScreen(actualScreen){
// This line doesn't work : because 'this' is immutable
this = actualScreen;
this.tapAddButton = function(){
this.getAddButton().tap();
}
//...
}
我会这样使用它:
var mainScreen = new MainScreen(app.mainWindow());
mainScreen.tapAddButton();
我以为我可以将actualScreen保存为对象的属性(就像下面的Grace Shao的回答一样),并对其调用所有方法,但是我想保留原始的UIAWindow方法。
有人知道怎么做这个吗? 也许我想要实现的目标没有意义,在这种情况下,我很高兴知道。
如果我理解正确,则可以尝试以下操作:
function MainScreen(actualScreen){
this.screen = actualScreen;
}
MainScreen.prototype.tapAddButton = function () {
this.screen.getAddButton().tap();
};
MainScreen.prototype.getScreen = function () {
return this.screen;
};
//...
var mainScreen = new MainScreen(app.mainWindow());
mainScreen.tapAddButton();
您是正确的,您不能this
分配任何内容。 您也可以在构造函数MainScreen
定义方法,但它们将被视为特权成员。
function MainScreen(actualScreen){
this.screen = actualScreen;
this.tapAddButton = function () {
this.screen.getAddButton().tap();
};
}
如果您不希望它们成为特权成员,则最好在构造函数之外定义它们。 否则,每次实例化一个新对象时,成员将一次又一次地初始化。
更新 :您还可以为构造函数内部的screen
方法封装,如下所示。
var prop;
for (prop in actualScreen) {
if (typeof actualScreen[prop] !== 'Function') {
continue;
}
this[prop] = function () {
return actualScreen[prop].apply(actualScreen, arguments);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.