Created
October 3, 2017 23:49
-
-
Save RP-3/8049934e911652ee755eb88048f4b479 to your computer and use it in GitHub Desktop.
Instantiation patterns and the keyword 'this'.
This file contains hidden or 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
// functional instatiation | |
var FunctionalCat = function(name){ | |
var result = {}; | |
result.name = name; | |
result.sayHi = function(){ | |
console.log(`Meow, my name is ${this.name}, the cat.`); | |
} | |
return result; | |
}; | |
var cat = FunctionalCat('Gabe'); | |
cat.sayHi(); | |
// shared functional | |
var catMethods = { | |
sayHi: function(){ | |
console.log(`Meow, my name is ${this.name}, the cat.`); | |
} | |
}; | |
var extend = function(methods, obj){ | |
for(var key in methods) obj[key] = methods[key]; | |
}; | |
var SharedFunctionalCat = function(name){ | |
var result = {}; | |
result.name = name; | |
extend(catMethods, result); | |
return result; | |
}; | |
var cat = SharedFunctionalCat('Goldie'); | |
cat.sayHi(); | |
// prototypal | |
var catMethods = { | |
sayHi: function(){ | |
console.log(`Meow, my name is ${this.name}, the cat.`); | |
} | |
}; | |
var PrototypalCat = function(name){ | |
var result = Object.create(catMethods); | |
result.name = name; | |
return result; | |
}; | |
var cat = PrototypalCat('rp3') | |
cat.sayHi(); | |
// inheritance | |
var tigerMethods = Object.create(catMethods, { | |
roar: function(){ console.log(this.size ? 'ROAR' : 'squeak'); } | |
}); | |
var ProtoTiger = function(name, size){ | |
var result = Object.create(tigerMethods); | |
result.size = size; | |
result.name = name; | |
return result; | |
} | |
// pseudoclassical | |
var ClassicalCat = function(name){ | |
// var this = Object.create(ClassicalCat.prototype); | |
this.name = name; | |
// return this; | |
}; | |
ClassicalCat.prototype.sayHi = function(){ | |
console.log(`Meow, my name is ${this.name}, the cat.`); | |
}; | |
var cat = new ClassicalCat('George'); | |
cat.sayHi(); | |
// inheritance | |
var ClassicalTiger = function(name, size){ | |
ClassicalCat.call(this, name); | |
this.size = size; | |
}; | |
ClassicalTiger.prototype.roar = function(){ | |
console.log(this.size ? 'ROAR' : 'squeak'); | |
}; | |
// discuss what 'this' is | |
// discuss what 'call' does. | |
// what about 'apply'? | |
// when is this useful or mandatory? | |
// how do you get the 'type' of an object in js? | |
// how you access the arguments passed to a function in js? | |
// beast mode, lets write a curry in JS! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment