javaScript中的this樣本學習詳解及工作原理_基礎知識

來源:互聯網
上載者:User

this的工作原理

如果一個函數被作為一個對象的方法調用,那麼this將被指派為這個對象。

複製代碼 代碼如下:

var parent = {
    method: function () {
        console.log(this);
    }
};

parent.method();
// <- parent


注意這種行為非常“脆弱”,如果你擷取一個方法的引用並且調用,那麼this的值不會是parent了,而是window全域對象。這讓大多數開發人員迷惑。

複製代碼 代碼如下:

ThisClownCar();
// <- Window
 

改動this

.call、 .apply 和.bind 方法用來操作調用函數的方式,幫我們定義this的值和傳遞給函數的參數值。

Function.prototype.call 可以有任意數量的參數,第一個參數被分配給this,剩下的被傳遞給調用函數。

複製代碼 代碼如下:

Array.prototype.slice.call([1, 2, 3], 1, 2)
// <- [2]

Function.prototype.apply 的行為和.call類似,但它傳遞給函數的參數是一個數組,而不是任意參數。

String.prototype.split.apply('13.12.02', ['.'])
// <- ['13', '12', '02']
 

Function.prototype.bind 建立一個特殊的函數,該函數將永遠使用傳遞給.bind的參數作為this的值,以及能夠分配部分參數,建立原函數的珂裡化(curride)版本。

 

複製代碼 代碼如下:

var arr = [1, 2];
var add = Array.prototype.push.bind(arr, 3);

// effectively the same as arr.push(3)
add();

// effectively the same as arr.push(3, 4)
add(4);

console.log(arr);
// <- [1, 2, 3, 3, 4]


範圍鏈中的this

在下面的例子,this將無法在範圍鏈中保持不變。這是規則的缺陷,並且常常會給業餘開發人員帶來困惑。

複製代碼 代碼如下:

function scoping () {
  console.log(this);

  return function () {
    console.log(this);
  };
}

scoping()();
// <- Window
// <- Window

有一個常見的方法,建立一個局部變數保持對this的引用,並且在子範圍中不能有同命變數。子範圍中的同名變數將覆蓋父範圍中對this的引用。http://www.cnblogs.com/sosoft/

複製代碼 代碼如下:

function retaining () {
  var self = this;

  return function () {
    console.log(self);
  };
}

retaining()();
// <- Window
 

除非你真的想同時使用父範圍的this,以及當前this值,由於某些莫名其妙的原因,我更喜歡是使用的方法.bind函數。這可以用來將父範圍的this指定給子範圍。

 

複製代碼 代碼如下:

function bound () {
  return function () {
    console.log(this);
  }.bind(this);
}

bound()();
// <- Window

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.