javascript - Why `this` keyword need to be evaluated inside this function? -


can me explain role of this keyword in snippet. i'm reading js: definitive guide , run one:

// define es5 string.trim() method if 1 not exist. // method returns string whitespace removed start , end. string.prototype.trim = string.prototype.trim || function()  {    if (!this)      return this; // why evaluate `this` in function???      return this.replace(/^\s+|\s+$/g, ""); }; 

well test

if (!this) return this; 

means if string empty returns this in case empty string.

if remove test, function still work, keeping make function faster because don't have call replace function when string empty.

note test if (!this) return this; isn't null or undefined values because don't have function inside them call proof can't :

undefined.trim(); null.trim(); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -