Last active
August 29, 2015 14:15
-
-
Save eliza-abraham/870fcfed5df653d49bdf to your computer and use it in GitHub Desktop.
JavaScript Prototype & 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
/* Important concepts about prototypes and this */ | |
// Problem Statement: console.log('hello'.repeatify(3)); Should print hellohellohello. | |
String.prototype.times = String.prototype.times || function(number) { | |
var str = ''; | |
for (var i = 0; i < number; i++) { | |
str += this; | |
} | |
return str; | |
}; | |
// Scope of this | |
var fullname = 'John Doe'; | |
var obj = { | |
fullname: 'Colin Ihrig' | |
prop: { | |
fullname: 'Aurelio De Rosa', | |
getFullname: function() { | |
return this.fullname; | |
} | |
} | |
}; | |
console.log(obj.prop.getFullname()); // Aurelio De Rosa | |
var test = obj.prop.getFullname; | |
console.log(test()); // John Doe, test implicitly assigned to the global object therefore calls the global fn. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment