Created
May 18, 2014 21:25
-
-
Save the-swerve/ab705dfe370c64be1ae4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively, even simpler: