大家好,小编来为大家解答以下问题,学前端还是后端好找工作,javascript基础入门教程,今天让我们一起来看看吧!

java指南
In JavaScript, every function has a this reference automatically created when you declare it.
在JavaScript中,每个函数在声明它时都会自动创建一个this引用。
JavaScript's this is quite similar to a this reference in other class-based languages such as Java or C# (JavaScript is a prototype-based language and no “class” concept): It points to the which object is calling to the function (this object sometimes called as context). In JavaScript, however, the this reference inside functions can be bound to different objects depending on where the function is being called.
JavaScript的this类似于其他基于类的语言(例如Java或C#)中的this引用(JavaScript是基于原型的语言,没有“类”概念): 它指向哪个对象正在调用函数 (此对象有时称为上下文 )GPT改写。 但是,在JavaScript中, this内部引用函数可以根据调用函数的位置绑定到不同的对象 。
Here are 5 basic rules for this binding in JavaScript:
以下是JavaScript中this绑定的5条基本规则:
规则1 (Rule 1)
When a function is called in the global scope, the this reference is by default bound to the global object (window in the browser, or global in Node.js). For example:
在全局范围内调用函数时,默认情况下, this引用绑定到全局对象 (浏览器中的window或Node.js中的global )。 例如:
function foo() {
this.a = 2;
}
foo();
console.log(a); // 2
Note: If you declare the foo() function above in strict mode, then you call this function in global scope, this will be undefined and assignment this.a = 2 will throw Uncaught TypeError exception.
注意:如果您在严格模式下声明了上面的foo()函数,那么您将在全局范围内调用此函数, this将是undefined ,分配this.a = 2将引发Uncaught TypeError异常。
规则二 (Rule 2)
Let’s examine example below:
让我们来看下面的示例:
function foo() {
this.a = 2;
}
const obj = {
foo: foo
};
obj.foo();
console.log(obj.a); // 2
Clearly, in the above snippet, the foo() function is being called with context is obj object and this reference now is bound to obj. So when a function is called with a context object, the this reference will be bound to this object.
显然,在上面的代码片段中,使用Context对象是obj对象的foo()函数被调用,并且this引用现在绑定到obj 。 因此,当使用上下文对象调用函数时, this引用将绑定到该对象。
规则三 (Rule 3)
.call, .apply and .bind can all be used at the call site to explicitly bind this. Using .bind(this) is something you may see in quite a lot of React components.
.call , .apply和.bind都可以在调用点使用明确绑定this 。 您可以在很多React组件中看到使用.bind(this)的东西。
const foo = function() {
console.log(this.bar)
}
foo.call({ bar: 1 }) // 1
Here’s a quick example of how each one is used to bind this:
这里的每个人是如何用来绑定一个简单的例子this :
-
.call():fn.call(thisObj, fnParam1, fnParam2)fn.call(thisObj, fnParam1, fnParam2).call():fn.call(thisObj, fnParam1, fnParam2) -
.apply():fn.apply(thisObj, [fnParam1, fnParam2]).apply():fn.apply(thisObj, [fnParam1, fnParam2]) -
.bind():const newFn = fn.bind(thisObj, fnParam1, fnParam2).bind():const newFn = fn.bind(thisObj, fnParam1, fnParam2)
规则四 (Rule 4)
function Point2D(x, y) {
this.x = x;
this.y = y;
}
const p1 = new Point2D(1, 2);
console.log(p1.x); // 1
console.log(p1.y); // 2
The thing you must notice that is the Point2D function called with new keyword, and this reference is bound to p1 object. So when a function is called with new keyword, it will create a new object and this reference will be bound to this object.
您必须注意的是使用new关键字调用的Point2D函数,并且this引用绑定到p1对象。 因此,当使用new关键字调用函数时,它将创建一个新对象,并且this引用将绑定到该对象。
Note: As you call a function with new keyword, we also call it as constructor function.
注意:当您使用new关键字调用函数时,我们也将其称为构造函数 。
规则五 (Rule 5)
JavaScript determines the value of this at runtime, based on the current context. So this can sometimes point to something other than what you expect.
JavaScript确定的值this在运行时,基于所述当前上下文。 因此, this有时可能指向您期望之外的其他内容。
Consider this example of a Cat class with a method called makeSound(), following the pattern in Rule 4 (above) with a constructor function and the new keyword.
考虑这个Cat类的示例,该示例使用名为makeSound()的方法,遵循规则4(上)中的模式,并带有构造函数和new关键字。
const Cat = function(name, sound) {
this.name = name;
this.sound = sound;
this.makeSound = function() {
console.log( this.name + ' says: ' + this.sound );
};
}
const kitty = new Cat('Fat Daddy', 'Mrrooowww');
kitty.makeSound(); // Fat Daddy says: Mrrooowww
Now let’s try to give the cat a way to annoy() people by repeating his sound 100 times, once every half second.
现在,让我们尝试通过每半秒钟重复100次发出声音来annoy()猫annoy() 。
const Cat = function(name, sound) {
this.name = name;
this.sound = sound;
this.makeSound = function() {
console.log( this.name + ' says: ' + this.sound );
};
this.annoy = function() {
let count = 0, max = 100;
const t = setInterval(function() {
this.makeSound(); // <-- this line fails with `this.makeSound is not a function`
count++;
if (count === max) {
clearTimeout(t);
}
}, 500);
};
}
const kitty = new Cat('Fat Daddy', 'Mrrooowww');
kitty.annoy();
That doesn’t work because inside the setInterval callback we’ve created a new context with global scope, so this no longer points to our kitty instance. In a web browser, this will instead point to the Window object, which doesn’t have a makeSound() method.
这并不工作,因为里面setInterval回调,我们已经创建了全球范围内新的上下文,因此this不再指向我们的猫咪实例。 在Web浏览器, this将改为指向窗口对象,该对象不具有makeSound()方法。
A couple of ways to make it work:
使其工作的几种方法:
-
Before creating the new context, assign
thisto a local variable namedme, orself, or whatever you want to call it, and use that variable inside the callback.创建新的上下文之前,分配
this名为局部变量me,或self,或任何你想将它命名,并使用回调内部的变量。
const Cat = function(name, sound) {
this.name = name;
this.sound = sound;
this.makeSound = function() {
console.log( this.name + ' says: ' + this.sound );
};
this.annoy = function() {
let count = 0, max = 100;
const self = this;
const t = setInterval(function() {
self.makeSound();
count++;
if (count === max) {
clearTimeout(t);
}
}, 500);
};
}
const kitty = new Cat('Fat Daddy', 'Mrrooowww');
kitty.annoy();
-
With ES6 you can avoid assigning
thisto a local variable by using an arrow function, which bindsthisto the context of the surrounding code where it’s defined.与ES6就可以避免分配
this通过使用箭头功能,其结合本地变量this到它的限定的周围的代码的情况下。
const Cat = function(name, sound) {
this.name = name;
this.sound = sound;
this.makeSound = function() {
console.log( this.name + ' says: ' + this.sound );
};
this.annoy = function() {
let count = 0, max = 100;
const t = setInterval(() => {
this.makeSound();
count++;
if (count === max) {
clearTimeout(t);
}
}, 500);
};
}
const kitty = new Cat('Fat Daddy', 'Mrrooowww');
kitty.annoy();
翻译自: https://www.freecodecamp.org/news/the-complete-guide-to-this-in-java/
java指南
本文详细解释了JavaScript中`this`关键字的行为,包括其在不同情况下的绑定规则,如全局作用域、对象上下文、函数调用方式(call、apply、bind)以及构造函数的使用。通过实例演示,帮助读者掌握`this`在实际编程中的运用。
5899

被折叠的 条评论
为什么被折叠?



