-1

I've recently been moving out of my comfort zone with JS, and come across a situation where it would make sense to share common functionality. What I've come up with is the following (concept only) code:

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://'; 
}

This code works as I expect it to work (making the "methods" on URL available on HttpURL, but not vice versa), but I wonder if it is "ethical" or if there is a better way of allowing this.

Norwæ
  • 1,575
  • 8
  • 18
  • And what's the question? Is it ethical for two objects to share the same code? ) – raina77ow Apr 01 '14 at 11:06
  • 1
    This is precisely how one would comfortably manage inheritance schemes in Javascript. Kudos! If you're working in older environments that don't support `Object.create`, you'll have a bit more work to do, but this is the right idea. – Scott Sauyet Apr 01 '14 at 11:07

1 Answers1

0

a situation where it would make sense to share common functionality.

subclass(URL, HttpURL)

Yes, that works and is the correct solution.

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

This code works as I expect it to work (making the "methods" on URL available on HttpURL, but not vice versa)

No. You want to make URL methods available on HttpUrl instances, for which you would need to use the prototype:

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

Otherwise they won't be inherited.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375