javascript
JavaScript中的“ this”关键字
JavaScript'this'關(guān)鍵字 (JavaScript 'this' keyword)
The this keyword is widely used in JavaScript. It has many use cases and is also one of the most intimidating features of JavaScript. In most of the programming languages, this is used to refer to the current instance of an object. Let me assure you though, that by the end of this article you'll be very confident in understanding this.
this關(guān)鍵字在JavaScript中被廣泛使用。 它具有許多用例,并且也是JavaScript最令人生畏的功能之一。 在大多數(shù)編程語言中, 這用于引用對象的當前實例。 不過,讓我向您保證,到本文結(jié)尾,您將對理解這一點非常有信心。
Let's first get a general idea of this. Let's say you have a class Car which has three data members model, type and price. The variable names for the model, type and price are the same. If we invoke the constructor function of Car to initialize the data members with some values, we can use this to refer to the current instance of Car. We can do something like this,
首先讓我們對此有一個大致的了解。 假設(shè)您有一個Car類,它具有三個數(shù)據(jù)成員model , type和price 。 模型的變量名稱, 類型和價格相同。 如果調(diào)用Car的構(gòu)造函數(shù)以一些值初始化數(shù)據(jù)成員,則可以使用它來引用Car的當前實例。 我們可以做這樣的事情,
class Car {var model, type, price;Car(model, type, price) {this - > model = model;this - > type = type;this - > price = price;} }We have used this to avoid confusion between the parameters passed to the constructor function and the data members of the class Car.
我們使用它來避免傳遞給構(gòu)造函數(shù)的參數(shù)與Car類的數(shù)據(jù)成員之間的混淆。
This is this, in a general context. Let's explore it in JavaScript now.
在一般情況下就是這樣 。 現(xiàn)在讓我們用JavaScript進行探索。
this is a reserved keyword in JavaScript that does a lot more than what we saw above.
這是JavaScript中的保留關(guān)鍵字,它的作用遠遠超過了上面的內(nèi)容。
Its value is determined by the execution context.
它的值由執(zhí)行上下文確定。
The execution context is determined by how a function is called or invoked? So we're associating this to functions instead of classes? Yes, remember that this in JavaScript comes into existence only when a function is defined. Every time that function definition runs, we get this defined for a function.
執(zhí)行上下文取決于如何調(diào)用或調(diào)用函數(shù)? 因此,我們將其與函數(shù)而不是類相關(guān)聯(lián)嗎? 是的,請記住,只有在定義函數(shù)后,JavaScript中的此功能才存在。 每當函數(shù)定義運行時,我們都會為函數(shù)定義該定義。
Before explaining the execution context and how this is associated with functions, let's see this in live-action.
在解釋執(zhí)行上下文以及它與函數(shù)的關(guān)系之前,讓我們在實際操作中看到它。
console.log(this);Output
輸出量
Window {parent: Window, postMessage: ?, blur: ?, focus: ?, close: ?, …}If you expand the window, you get a whole load of methods and properties. Every time we talk about this, we picture its scope. The scope of this is defined as what object it refers to. Since we wrote absolutely nothing above, this refers to the global or window object.
如果展開窗口,則會得到大量的方法和屬性。 每次我們談?wù)撨@個問題時 ,我們都會了解它的范圍。 這個范圍是指什么反對它指的是。 由于我們在上面絕對沒有寫任何內(nèi)容, 因此它是指全局或窗口對象。
Alright, so you have three golden rules to determine the context of this. Let's look at these rules one by one,
好了,所以你有三條黃金規(guī)則來確定這樣的背景下。 讓我們一一看這些規(guī)則,
1) The Global Rule
1)全球規(guī)則
Unless we have this inside of an object, it will point or refer to the global object and the global object in JavaScript is the Window object. The example we saw above describes the global rule.
除非我們在對象內(nèi)部擁有此對象,否則它將指向或引用全局對象,而JavaScript中的全局對象是Window對象。 我們上面看到的示例描述了全局規(guī)則。
function Person() {this.person = 'Fuzzy';//this points to global object }Person(); console.log(person);Output
輸出量
FuzzyPerson becomes a global variable as it is declared on the global object. We have this nowhere close to any kind of object whatsoever. We have a function, so this comes into existence and it looks for an object to associate its scope with. It finds no such object and attaches itself to the Window object as per the global rule.
人員在全局對象上聲明時成為全局變量。 我們有這個無處接近任何類型的對象任何的。 我們有一個功能,所以這個就開始存在,它尋找一個對象與范圍相關(guān)聯(lián)。 它找不到這樣的對象,并根據(jù)全局規(guī)則將其自身附加到Window對象。
2) Implicit Binding
2)隱式綁定
Whenever we declare this inside of a declared object, the value of this becomes close to that of it's parent object.
每當我們在已聲明的對象內(nèi)部聲明此值時,此值的值就會接近其父對象的值。
var person = {name: 'Fuzzy',greet: function() {return 'Hello' + this.name;},scopeThis: function() {return this === person;} }person.greet(); person.scopeThis();Output
輸出量
"HelloFuzzy" trueWe have a function greet() where we use this. So this comes into existence and gets associated with the function greet(). It bubbles up to see if it is attached to any object and finds itself wrapped inside the object person. So the scope of this, in this case, is the object person according to implicit binding rule.
我們在其中使用this的函數(shù)greet() 。 因此,它就存在并與函數(shù)greet()關(guān)聯(lián)。 冒泡看看它是否附著在任何對象上,并發(fā)現(xiàn)它被包裹在對象人體內(nèi)。 所以這個范圍,在這種情況下,是根據(jù)隱式綁定規(guī)則的對象的人。
What will be the scope of this in the next example?
什么將是這個在下面的例子范圍有多大?
var person= {Name: 'Fuzzy', scopeThis: this }person.scopeThis;Output
輸出量
Window {parent: Window, postMessage: ?, blur: ?, focus: ?, close: ?, …}Did you guess the scope of this to be person? Remember, this only comes into existence when a function is associated with it. Since scopeThis is not a function, this assumes it's usual value. The implicit binding rule does not hold true and this takes the value of the global or window object using the global rule.
你猜這是人的范圍嗎? 請記住, 這只是開始存在當一個函數(shù)與它關(guān)聯(lián)。 由于scopeThis不是函數(shù),因此假定它是通常的值。 隱式綁定規(guī)則不成立, 它使用全局規(guī)則獲取全局或窗口對象的值。
3) Explicit Binding
3)顯式綁定
We can choose what we want the context of this to be using call(), apply() and bind(). We invoke these methods only on functions.
我們可以使用call(),apply()和bind()選擇我們想要的上下文。 我們僅在函數(shù)上調(diào)用這些方法。
call(): Takes thisArg, a, b,c,d,... as parameters and is invoked immediately.
call() :將thisArg,a,b,c,d,...作為參數(shù),并立即調(diào)用。
apply(): Takes thisArg,[a,b,c,d,...] as parameters and is invoked immediately.
apply() :將thisArg,[a,b,c,d,...]作為參數(shù),并立即調(diào)用。
bind(): Takes thisArg,a,b,c,d, ... as parameters and is invoked after some time returns a function definition.
bind() :將thisArg,a,b,c,d,...作為參數(shù),并在一段時間后調(diào)用,返回一個函數(shù)定義。
Output
輸出量
false trueperson.dog.scopeThis() returns false since this takes the binding of the dog object according to our Implicit Binding rule and person.dog.scopeThis().call() returns true as we're explicitly setting the value of context of this to be that of the object person.
person.dog.scopeThis()返回false,因為這將根據(jù)我們的隱式綁定規(guī)則進行dog對象的綁定,而person.dog.scopeThis()。call()返回true,因為我們明確設(shè)置了此對象的上下文值成為客體的人 。
Another example where we can use call() to also explicitly set the value of this to be anything as per our wish.
在這里我們可以使用()的調(diào)用也明確設(shè)置這個值的另一個例子是什么,按照我們的心愿。
var person={name: 'Fuzzy',greet: function(){return 'Hello' + this.name; } }var dog={name: ' Cooper' } person.greet.call(dog);Output
輸出量
"Hello Cooper"We called greet() function, a member of the person object but returned the name of dog object using this. We explicitly bind this to an external object dog using call().
我們將greet()函數(shù)稱為person對象的成員,但使用this返回了dog對象的名稱。 我們使用call()將其明確綁定到外部對象dog 。
var person = {name: 'Fuzzy',greet: function() {setTimeout(function() {console.log('Hello' + this.name);}, 1000);} } person.greet()Output
輸出量
'Hello'In the above example, we get the value of this to be undefined and we get the Hello undefined on the console. Can you guess why?
在上面的示例中,我們獲得了this的值未定義,并且在控制臺上獲得了Hello未定義 。 你能猜出為什么嗎?
By the time our setTimeout() function runs, we have lost the binding of this to it's closest parent object. Hence the closest parent object of this is the global or the window object and name is not a defined property for this anymore. A workaround this would using the bind() method.
到時候我們的setTimeout()函數(shù)運行,我們已經(jīng)失去了這個給它最親密的父對象的綁定。 因此, 此對象的最接近的父對象是全局對象或窗口對象,并且name不再是為此定義的屬性。 解決方法是使用bind()方法。
var person = {name: 'Fuzzy',greet: function() {setTimeout(function() {console.log('Hello' + this.name);}.bind(this), 1000);} }Output
輸出量
'Hello Fuzzy'Now we get Hello Fuzzy exactly how we wanted it.
現(xiàn)在,我們確切地得到了Hello Hello 。
In addition to all this, if we define an object using the new keyword we get the general meaning of this. this automatically binds itself to the current instance of the object defined using the new keyword.
除了這一切,如果我們使用new關(guān)鍵字定義對象,我們得到的這個一般意義。 這會自動將自身綁定到使用new關(guān)鍵字定義的對象的當前實例。
Remember to use all the rules independently while checking the scope of this.
在檢查范圍時,切記要獨立使用所有規(guī)則。
I hope this wasn't too hard(pun intended).
我希望這不太難(雙關(guān)語意)。
翻譯自: https://www.includehelp.com/code-snippets/this-keyword-in-javascript.aspx
總結(jié)
以上是生活随笔為你收集整理的JavaScript中的“ this”关键字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gcc -pthread_错误-在GCC
- 下一篇: java uuid静态方法_Java U