2017-03-16 140 views
0

我工作的一個UI自動化項目,我想從另一個頁面對象擴展一個頁面對象。我搜索的方式來實現這一點,但無法找到我正在尋找什麼。 基本上我有這樣的代碼設置。擴展(繼承)類(或對象)在Javascript

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

define([], 
     function() { 

      function LoginPage(remote) { 
      this.remote = remote; 

      } 

      LoginPage.prototype = { 
       constructor: BasePage, 
      // Login Page related Methods 

      loginPageRelatedMethod: function{ 
       return doSomething; 
      } 
    }; 

    return LoginPage; 
}); 

我想只是這樣做是爲了繼承BasePage的方法LoginPage

var loginPage = new LoginPage(remote); 
loginPage.commonMethodToIntreactWithPage(); 

只是爲了我的信息使用Intern.js進行測試。

+1

你可以試試'LoginPage.prototype =新的BasePage()' – amenadiel

回答

1

您需要定義是這樣的。第一行將創建的屬性和方法,這是在BasePage.prototype並設置原型參照該一個新對象,所以每LoginPage對象將具有那些性質和對象。畢竟我加入其中僅涉及LoginPageloginPageRelatedMethod)所有的特定數據。而且設置正確的constructor也很重要。

LoginPage.prototype = Object.create(BasePage.prototype); 

LoginPage.prototype.constructor = LoginPage; 

LoginPage.prototype.loginPageRelatedMethod = function(){ 
    return doSomething; 
} 

修訂

function LoginPage(remote) { 
    BasePage.call(this, remote); 
} 

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());

+0

請注意,'對象。創建第二個參數元素不能是任何對象,它必須是_property描述符的對象,而'BasePage.prototype'不是這樣的對象。請檢查該SO回答更多的細節:http://stackoverflow.com/questions/17408350/object-create-bug –

+0

@BartekFryzowicz對不起,我misstyped東西,第一個參數應該是BasePage.prototype' –

+0

@SurenSrapyan這一切'應該包含在'LoginPage.js'中? – CodeBlooded