内置函数中的“ this”关键字

时间:2018-11-21 07:58:40

标签: javascript

我不太了解内置函数(例如String,Number等)中的'this'关键字如何直接指向原始值,而不是像'this'关键字那样指向对象。它是由JavaScript引擎直接设置的吗?

我有这个例子:

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

我期望chrome devtools中的输出为[object Object][object Object][object Object]

2 个答案:

答案 0 :(得分:1)

this有很多东西,但实际上它是函数调用的目标。

一些例子:

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

答案 1 :(得分:-1)

var string = 'hello'; // ------------
// this refers to the               |
// ----------v--string itself => 'hello'
console.log(string.repeatify(3));

您要在String原型上定义repeatify,所以这只是String的一种。因此,它将记录hellohellohello