Last active
June 20, 2016 12:47
-
-
Save rowlandekemezie/790c71f2a1a6146189e003e462239c40 to your computer and use it in GitHub Desktop.
Awesome use of arguments and prototypal inheritance in javascript
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
// It's worthy of note that Javascript is not a class-oriented language. It's strength is in its native nature. | |
// Basically, Javascript is a prototypal language and thus uses prototypal inheritance for its operations. | |
// The example below is a tip of how the prototypal nature of javascript can be utilized | |
// Implementing the use of 'arguments' object to pass arguments to a funcion | |
function foo() { | |
bar.apply(null, arguments) | |
} | |
function bar(){ | |
console.log(Array.prototype.slice.call(arguments)); | |
var total = 1; | |
for(var i = 0; i< arguments.length; i++){ | |
console.log(total *= arguments[i]) | |
} | |
} | |
foo(3, 4, 5, 6, 4, 4, 7, 7); | |
// Returns | |
// 12 | |
// 60 | |
// 360 | |
// 1440 | |
// 5760 | |
// 40320 | |
// 282240 | |
// Implementing class for a Person constructor and leveraging call and apply function on Function | |
function Person (first, last){ | |
this.first = first; | |
this.last = last; | |
} | |
Person.prototype.fullname = function(seperator, race) { | |
race = race || { type: "western" }; | |
var first = options.type === "western" ? this.first : this.last; | |
var last = options.type === "western" ? this.last : this.first; | |
return first + (separator || " ") + last; | |
}; | |
Person.fullname = function(){ | |
// This returns unbound version of fullname method. | |
// Basically, it returns Person.prototype.call(this, separator, args) | |
return Function.call.apply(Person.prototype.fullname, arguments); | |
}; | |
var newPerson = new Person('Bushimu', 'Ababdik'); | |
newPerson.fullname(); // Returns Bushimu Ababdik | |
Person.fullname({first: 'Cruzzy', last: 'Wambulla'}, '-', {type: 'easten'}); // Returns Wambulla-Cruzzy | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment