新聞中心
this應(yīng)該是一個討論了很久的話題了。其中,關(guān)于this的文章,在很多的博客當(dāng)中也有很多介紹,但是,以前我都是一知半解的去了解它,就是看博客當(dāng)中,只介紹了一些情況下的 this 的使用方式,但是也并沒有自己去做過總結(jié)。剛好是在掘金當(dāng)中有看到一篇關(guān)于this的一些詳細(xì)文章,文末會附上鏈接以及英文原文,這里純粹是自己進(jìn)行一個總結(jié),以后方便自己進(jìn)行回顧以及加深印象。希望這篇文章對于你了解this有一定的幫助,文末還有一些練習(xí)題噢~希望真的對你們有幫助。(因為寫項目過程中,一直被 this 坑過,卻找了很久的 bug ,我真是 樂了狗)

為市南等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及市南網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、做網(wǎng)站、市南網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
在了解this之前,相信大家都應(yīng)該會知道作用域這個知識點的存在,函數(shù)在創(chuàng)建之后,會構(gòu)建自己的執(zhí)行環(huán)境以及作用域,這是一開始就確定了。但是實際的上下文(context)環(huán)境,也可以理解為就是this,它是動態(tài)確定的,即在函數(shù)運行時才確定this所指向的對象,而非聲明時所指向的對象。
關(guān)于this,總結(jié)起來,主要有以下幾個途徑能夠被運用到。
1 對象方法中調(diào)用this
如果函數(shù)被當(dāng)中對象的一個方法進(jìn)行調(diào)用,則this值指向該對象。
- var person = {
- name: 'Alice',
- sayName: function() {
- alert('welcome ' + this.name);
- }
- }
- person.sayName(); // this == person, alert: 'welcome Alice'
在這里,函數(shù)的this指向該對象(即 person);但是有一點需要注意,就是當(dāng)對象的方法被賦予給一個變量時,其則變?yōu)榱撕瘮?shù)觸發(fā),此時的this為 window 或者 undefined(嚴(yán)格模式下),如下:
- var name = 'Bob';
- var person; // 即上面的定義,此不拓展詳細(xì),直接使用
- var say = person.sayName; // this == window || undefined
- say(); // 'welcome Bob' || throw an error: Cannot read property 'name' of undefined(...)
2 函數(shù)內(nèi)部使用
在函數(shù)內(nèi)部當(dāng)中使用了 this,即函數(shù)被當(dāng)做方法使用,不同于 1 當(dāng)中作為對象的方法使用,此時調(diào)用,是在全局作用域下進(jìn)行調(diào)用,即在window下進(jìn)行調(diào)用,由定義可以知道,在全局作用域下聲明一個函數(shù),其自動加為window的一個屬性。this此時名正言順的會指向window,嚴(yán)格模式下為 undefined
- function sayThis() {
- alert(this == window); // true
- }
結(jié)合第一點,函數(shù)作為對象的一個方法使用,這里存在一個小坑,即閉包,啥是閉包,這個在這里就不扯開了,最簡單的理解就是Function that returns function,如果不理解什么是閉包的話,可以去翻翻 《JavaScript 高級程序設(shè)計》第七章關(guān)于閉包的相關(guān)內(nèi)容。第一點當(dāng)中存在一個小坑,就是將對象的方法賦予給一個變量的時候,其變?yōu)楹瘮?shù)觸發(fā),此時的 this 實際上是指向 window(非嚴(yán)格模式)。
那么,當(dāng)函數(shù)中返回一個函數(shù),此時在對象當(dāng)中調(diào)用該方法,其就相當(dāng)于是函數(shù)觸發(fā),此時的 this,在不做任何上下文綁定的前提之下,其指向 window(非嚴(yán)格模式)。
- var name = 'Bob',
- person = {
- name: 'Alice',
- sayName: function() {
- console.log(this === person); // true
- return function() {
- console.log(this === person); // false
- console.log(this === window); // true
- console.log(this.name); // Bob
- };
- }
- };
- person.sayName()();
當(dāng)然,要解決這個問題的方法,很簡單,就是給他綁定一個上下文。
- var name = 'Bob',
- person = {
- name: 'Alice',
- sayName: function() {
- console.log(this === person); // true
- return function() {
- console.log(this === person); // true
- console.log(this === window); // false
- console.log(this.name); // Alice
- }.bind(this);
- }
- };
- person.sayName()();
3 new 當(dāng)中進(jìn)行使用
我們知道在使用 new 方法創(chuàng)建對象的時候,會經(jīng)過如下這些個過程:
- 創(chuàng)建對象,將 this 值賦予新的對象
- 調(diào)用構(gòu)造函數(shù),為 this 添加屬性和方法
- 返回 this 給當(dāng)前的對象
- function Person(name, age) {
- this.name = name;
- this.age = age;
- }
- var person1 = new Person('Alice', 29);
- console.log(person1.name); // Alice
這里要記得使用 new 運算符,否則,其只能算是普通的調(diào)用,而不是創(chuàng)建一個新的實例對象。而當(dāng)做普通函數(shù)調(diào)用的話,實際上即 第 2 種情況下,對函數(shù)普通調(diào)用,此時的 this 指向 window
- function Person(name, age) {
- this.name = name;
- this.age = age;
- return this;
- }
- var person1 = Person('Alice', 29);
- console.log(person1.name); // Alice
- console.log(window.name); // Alice
- console.log(person1 === window); // true
這是正常情況下,this 會正確返回并且指向該對象,但是在構(gòu)造函數(shù)當(dāng)中,如果返回了一個對象,那么 this 會指向返回的那個對象。
- function Person(name, age) {
- this.name = name;
- this.age = age;
- return {
- name: 'Bob'
- };
- }
- var person1 = new Person('Alice');
- console.log(person1.name); // Bob
- console.log(person1.age); // undefined
題外話,類似的,聯(lián)想到 var a = new Person(),則 a instanceof Person一定返回 true嗎?留給你們想一想咯。
4 使用 call、apply 或 bind 改變 this
在引用類型 Function當(dāng)中,函數(shù)存在兩個方法屬性,call 和 apply,在 ECMAScript5當(dāng)中,加入了 bind 方法。題外話,他們?nèi)邊^(qū)別,應(yīng)該都知道了吧,不知道的加緊補習(xí)呀。
- var name = 'Bob';
- var person = {
- name: 'Alice',
- age: 29
- }
- function sayName() {
- console.log(this.name);
- }
- sayName.call(person); // Alice
這里是使用了 call 方法來改變了 this的執(zhí)行環(huán)境,至于使用 apply,效果一樣,只是二者差別在于傳入?yún)?shù)的不同。
- func.call(context, arg1, arg2, ...)
- func.apply(context, [arg1, arg2, ...])
使用 bind 方法進(jìn)行上下文的改變,bind 方法與 call 和 apply有著本質(zhì)的不同,其不同點是,bind()函數(shù)返回的是一個新的函數(shù),即方法,而后兩者則都是立即執(zhí)行函數(shù),使用的時候即調(diào)用了該函數(shù),返回方法操作的結(jié)果。
并且,使用 bind()方法創(chuàng)建的 上下文,其為永久的上下文環(huán)境,不可修改,即使是使用 call 或者 apply方法,也無法修改 this所指向的值。
- var name = 'Bob';
- var person = {
- name: 'Alice',
- age: 29
- }
- function sayName() {
- console.log(this.name);
- }
- var say = sayName.bind(person);
- say(); // Alice
- sayName(); // Bob
5 箭頭函數(shù)
箭頭函數(shù)并不創(chuàng)建其自身的上下文,其上下文 this,取決于其在定義時的外部函數(shù)。
并且,箭頭函數(shù)擁有靜態(tài)的上下文,即一次綁定之后,便不可再修改,即使是用了 第 4 種用途當(dāng)中的改變上下文的方法,也不為之動容。
- var num = [1, 2, 3];
- (function() {
- var showNumber = () => {
- console.log(this === num); // true
- console.log(this); // [1, 2, 3]
- }
- console.log(this === num); // true
- showNumber(); // true && [1, 2, 3]
- showNumber.call([1, 2]); // true && [1, 2, 3]
- showNumber.apply([1, 2]); // true && [1, 2, 3]
- showNumber.bind([1, 2])(); // true && [1, 2, 3]
- }).call(num);
由于箭頭函數(shù)的外部決定上下文以及靜態(tài)上下文等的特性,不太建議使用箭頭函數(shù)在全局環(huán)境下來定義方法,因為不能通過其他方法改變其上下文。這很蛋疼。
- function Period (hours, minutes) {
- this.hours = hours;
- this.minutes = minutes;
- }
- Period.prototype.format = () => {
- console.log(this === window); // => true
- return this.hours + ' hours and ' + this.minutes + ' minutes';
- };
- var walkPeriod = new Period(2, 30);
- console.log(walkPeriod.hours);
- walkPeriod.format(); // => 'undefined hours and undefined minutes'
此時的 this 實際上是指向了 window,所以 this.hours 和 this.minutes實際上沒有聲明的,故為 undefined。
在全局環(huán)境下,還是選用 函數(shù)表達(dá)式 來進(jìn)行函數(shù)的定義,可以保證正確的上下文環(huán)境
- function Period (hours, minutes) {
- this.hours = hours;
- this.minutes = minutes;
- }
- Period.prototype.format = function() {
- console.log(this === walkPeriod); // => true
- return this.hours + ' hours and ' + this.minutes + ' minutes';
- };
- var walkPeriod = new Period(2, 30);
- walkPeriod.format(); // '2 hours and 30 minutes'
練習(xí)
- // 練習(xí)1
- var func = (function(a) {
- this.a = a;
- return function(a) {
- a += this.a;
- return a;
- }
- })(function(a, b) {
- return a;
- }(1, 2))
- func(4) // ?
- // 練習(xí)2
- var x = 10,
- foo = {
- x: 20,
- bar: function() {
- var x = 30;
- return this.x;
- }
- }
- console.log(foo.bar());
- console.log((foo.bar)());
- console.log((foo.bar = foo.bar)());
- console.log((foo.bar, foo.bar)());
希望看完這篇文章,這兩個練習(xí)題,你是能夠做出來的呀~ 好好分析一下唄。如果不確定的話,可以在留言板上,咱們相互討論一下呀
新聞標(biāo)題:Knowthis,usethis!(總結(jié)this的常見用法)
文章URL:http://fisionsoft.com.cn/article/cdieigj.html


咨詢
建站咨詢
