Javascript ';这';关键字内置函数
我不太明白内置函数中的'this'关键字(如String、Number等)如何直接指向基元值,而不是像'this'关键字那样的对象。它只是由javascript引擎直接设置的吗 我举了一个例子:Javascript ';这';关键字内置函数,javascript,Javascript,我不太明白内置函数中的'this'关键字(如String、Number等)如何直接指向基元值,而不是像'this'关键字那样的对象。它只是由javascript引擎直接设置的吗 我举了一个例子: String.prototype.repeatify = function(times) { console.log(this); // Output - String {"hello"} var str = ""; for(var i=0; i<times; i++)
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
String.prototype.repeatify=函数(次){
log(this);//输出-字符串{“hello”}
var str=“”;
对于(var i=0;i
您在字符串原型上定义了repeatify
,因此这只是一种字符串类型。因此,它将记录hellohello
,这有很多内容,但它本质上是函数调用的目标
一些例子:
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
此
是函数的当前范围,当您在字符串
类型上运行它时,此
是字符串本身此
不是对象{}
或字符串{}
内置函数???@roanshaz为什么您认为此
应该是[对象对象]
因为这正是您所期望的。@KarelG我认为“this”总是绑定到创建它的对象上(意思是“this”指向字符串{}
对象这与this
几乎没有关系,所有这些都与基本类型的隐式(un)有关装箱到对象/从对象以及+
运算符如何隐式获取对象的基本值。现在,这看起来可能是一条注释(重复项比这个答案更具解释性),因此在String.prototype.whatever=function()中{返回this+'ugh..which.'/'this'是调用此方法所针对的字符串}
如何获取此字符串的长度???this
是字符串,因此this.length
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