Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the-swerve/ab705dfe370c64be1ae4 to your computer and use it in GitHub Desktop.
Save the-swerve/ab705dfe370c64be1ae4 to your computer and use it in GitHub Desktop.
// Using a constructor function + prototype property + "new"
var Fruit = function(shape) {
if (!this instanceof Fruit) return new Fruit()
this.shape = shape
return this
}
Fruit.prototype.taste = 'sweet'
Fruit.prototype.eat = function() {
return 'it tastes ' + this.taste
}
var Apple = function(texture) {
if (!this instanceof Apple) return new Apple()
this.texture = texture
return this
}
Apple.prototype = Fruit() // inherit from Fruit
Apple.prototype.eat = function() {
return 'it tastes ' + this.taste + ' and ' + this.texture
}
var myapple = Apple('crunchy')
myapple.eat()
// 'it tastes sweet and crunchy'
// Using Object.create
// This would be globally available to help make inherited constructors
var Obj = {new: function() {return Object.create(this)}}
var Fruit = Obj.new()
Fruit.new = function(shape) {
this.shape = shape
Obj.new.call(this)
}
Fruit.eat = function() {
return 'it tastes ' + this.taste
}
var Apple = Fruit.new('round')
Apple.new = function(texture) {
this.texture = texture
Fruit.new.call(this, this.shape) // Apple inherits Fruit's constructor
}
Apple.eat = function() {
return 'it tastes ' + this.taste + ' and ' + this.texture
}
myapple = Apple.new('mushy')
myapple.eat()
// 'it tastes sweet and mushy'
@the-swerve
Copy link
Author

Alternatively, even simpler:

var Fruit = {taste: 'sweet'}
Fruit.eat = function() { return 'it tastes ' + this.taste}

var Apple = Object.create(Fruit)
Apple.shape = 'round'
Apple.eat = function() { return 'it tastes ' + this.taste + ' and ' + this.texture}

var myapple = Object.create(Apple)
myapple.texture = 'mushy'
myapple.eat()
// 'it tastes sweet and mushy'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment