2014-04-01 53 views
-1

我最近一直在用JS來擺脫我的舒適區,並遇到了共享通用功能的情況。我想出的是以下(觀止)代碼:JS「繼承」(代碼共享)機制

function subclass(parent, child) { 
    child.prototype = Object.create(parent.prototype) 
} 

function URL(str) { 
    this.value = str; 
} 

function HttpURL(str) { 
    this.value = str 
} 

subclass(URL, HttpURL) 

URL.path = function() { 
    return this.value; 
} 
// ... 

HttpURL.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
} 

此代碼的工作,因爲我期望它的工作(做對URL的「方法」上HttpURL可用,但不是反之亦然),但我想知道這是否「道德」,或者是否有更好的方法來允許這樣做。

+0

有什麼問題嗎?兩個對象共享相同的代碼是否合乎道德? ) – raina77ow

+1

這正是如何在Javascript中輕鬆管理繼承方案的方式。獎勵!如果您在不支持'Object.create'的較舊環境中工作,那麼您需要做更多工作,但這是正確的想法。 –

回答

0

這種情況下,共享通用功能是有意義的。

subclass(URL, HttpURL) 

是的,這工作,是correct解決方案。

URL.path = function() { 
    return this.value; 
} 
HttpURL.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
} 

此代碼的工作,因爲我期望它的工作(使上URL 的「方法」上HttpURL可用,但不是反之亦然)

號你想使URL方法可在HttpUrl 實例,而您將需要使用的原型:

URL.prototype.path = function() { 
    return this.value; 
} 
HttpURL.prototype.isSecure = function() { 
    this.value.substring(0, 8) === 'https://'; 
} 

否則,他們禾不被遺傳。