1. 程式人生 > >this的指向問題及修改指向

this的指向問題及修改指向

parse radix 等價 parseint app block 三種 scrip int

this指的當前對象,如果在全局訪問內使用this,則指向當前頁面的window; 如果在函數中使用this,則this是指代什麽是根據當前函數在什麽對象上調用。

1 console.log(this === window); // true
2 console.log(window.alert === this.alert); // true
3 console.log(this.parseInt(‘021‘, 10)); //21
parseInt(string, radix);
// 在只使用一個參數時,是將其轉為整數
// radix取值是2~36,表示當前數是幾進制,並將這個數轉為十進制,當不在這個範圍時,會輸出NaN

函數中的this是運行時決定的,而不是函數定義時。

 1 foo() {
 2     console.log(this.name);
 3 }
 4 var name = ‘global‘;
 5 foo(); // global
 6 var obj = {
 7     name: ‘block‘,
 8     foo: foo
 9 };
10 obj.foo(); // block

全局函數call和apply可以改變this的指向:

1 foo() {
2     console.log(this.name);
3 }
4 var name = ‘global‘;
5 var obj = {
6 name: ‘block‘ 7 }; 8 foo.apply(window); // global 9 foo.call(obj); // block

call和apply的唯一區別是,apply在傳參數時,apply的參數要放在一個數組裏,而call不需要。

在JavaScript中,函數也是個對象:

 1 function foo() {
 2      if (this === window) {
 3         console.log(this is window);
 4     }
 5 }
 6 foo.boo= function() {
 7     if (this
=== window) { 8 console.log(this is window); 9 } else { 10 console.log(this is foo); 11 } 12 } 13 // 等價於 window.foo 14 foo(); // this is window 15 16 foo.boo(); // this is foo 17 18 // 可以用call改變函數中this指向 19 foo.boo.call(window); // this is window

對象中的嵌套函數的this指向不是當前對象,而是window

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return function() {
 7             console.log(this.name)
 8         }
 9     }
10 };
11 obj.getName()(); // obj   window     

解決上述問題的三種方法:

1、使用函數的bind方法,綁定當前this

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return function() {
 7             console.log(this.name)
 8         }.bind(this);
 9      }
10  };
11 obj.getName()(); // obj   obj

2、使用變量將上面的this接收一下,然後下面不適用this,使用那個變量

3、使用ES6的箭頭函數

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return () => {
 7             console.log(this.name)
 8         }
 9     }
10 };
11 obj.getName()(); // obj   obj 

this的指向問題及修改指向