-1

I don't quite understand how does the 'this' keyword in built-in functions like String, Number, etc point to the primitive value directly instead of the object like the 'this' keyword is supposed to. Is it just directly set by javascript engine?

I have this example:

String.prototype.repeatify = function(times) {
    console.log(this);   // Output - String {"hello"}
    var str = "";
    for(var i=0; i<times; i++) {
        str += this;     //how does 'this' gets set to 'hello' and not the object- String{  }??
    }
    return str;
}
var string = new String('hello');
console.log(string.repeatify(3));   //Output - prints hellohellohello

I was expecting the output in the chrome devtools to be [object Object][object Object][object Object]

roan shaz
  • 66
  • 5

2 Answers2

1

There's a lot to this, but it's essentially the target of the function invocation.

Some examples:

String.prototype.whatever = function() {
  return this + ' ugh.. whatever.'
  // `this` is the string this method is called against
}

Array.prototype.slip = function() {
  return ['Hellooo', ...this];
  // `this` is the array in which the function is invoked on
}

function doSomething() {
  console.log(this + ' something');
  // `this` is whatever the function is bound to
}

console.log('Excuse me'.whatever()) // Excuse me ugh.. whatever.
console.log([1, 2, 3].slip()) // ["Hellooo", 1, 2, 3]

// In this case, the string 'I will do' becomes `this` in the doSomething function above as it's explicitly bound
doSomething.bind('I will do')(); // I will do something
Phix
  • 7,757
  • 3
  • 31
  • 57
  • so when inside the `String.prototype.whatever = function() { return this + ' ugh.. whatever.' // 'this' is the string this method is called against }` how would one get the length of this string ??? – marvinIsSacul Nov 21 '18 at 08:27
  • 1
    `this` is the string, so `this.length` – Phix Nov 21 '18 at 08:37
-1
var string = 'hello'; // ------------
// this refers to the               |
// ----------v--string itself => 'hello'
console.log(string.repeatify(3));

You're defining repeatify on String prototype so this is just a type of String. Thus, it will log hellohellohello.

Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
  • Now this looks like it could have been a comment (and the duplicate is more explanatory than this answer) – Icepickle Nov 21 '18 at 08:16