Skip to content

Instantly share code, notes, and snippets.

@eliza-abraham
Last active August 29, 2015 14:15
Show Gist options
  • Save eliza-abraham/870fcfed5df653d49bdf to your computer and use it in GitHub Desktop.
Save eliza-abraham/870fcfed5df653d49bdf to your computer and use it in GitHub Desktop.
JavaScript Prototype & this
/* 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