Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Last active October 6, 2015 03:38
Show Gist options
  • Save FireyFly/2929685 to your computer and use it in GitHub Desktop.
Save FireyFly/2929685 to your computer and use it in GitHub Desktop.
Using `extend` for "subclassing"
var Person = Base.inherit({
// missing: name
// A person can tell you its name.
talk: function() {
return "Hello, I'm " + this.name
}
})
var WorkingPerson = Person.inherit({
// missing: name, occupation
// A working person also tells you their occupation when they talk.
talk: function() {
return Person.talk.call(this) + " and I am a " + this.occupation
}
})
var p1 = WorkingPerson.inherit({ name:"Harry", occupation:"wizard" })
p1.talk() // "Hello, I'm Harry and I am a wizard"
var Base = {}
// Base#inherit
Object.defineProperty(Base, 'inherit', {
enumerable: false,
value: function(obj) {
var descs = {}
Object.getOwnPropertyNames(obj).forEach(function(key) {
descs[key] = Object.getOwnPropertyDescriptor(obj, key)
})
return Object.create(this, descs)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment