Jquery第四課 Javascript中this的使用方法

來源:互聯網
上載者:User

標籤:query   pen   code   cti   ace   block   str   數列   mono   

thiskeyword的使用

在JavaScript中使用thiskeyword表示調用方法的對象,這與大部分物件導向語言是一樣的。可是因為call、apply、bind等函數的影響。我們能夠改變this所代指的對象。

  • 使用call或者apply調用的函數中,this代指傳入的第一個參數對象,假設傳入null或者undefined。則表示全域對象(window)。
  • 通過對象調用函數(方法),函數中的this表示調用該函數的對象。

  • 單獨調用的函數中this表示全域對象。
var myObject = {    sayHello: function() {        console.log("Hi, my name is " + this.myName);    },    myName: "Rebecca"};var secondObject = {    myName: "Colin"};myObject.sayHello();    //"Hi, my name is Rebecca"myObject.sayHello.call(secondObject);   //"Hi, my name is Colin"
var myName = "the global object";var sayHello = function() {    console.log("Hi, my name is " + this.myName);};var myObject = {    myName = "Rebecca"};var myObjectHello = sayHello.bind(myObject);sayHello(); //"Hi, my name is the global object"myObjectHello(); //"Hi, my name is Rebecca"

JavaScript能夠在執行中為對象動態加入函數,這樣也會導致this代指的對象發生變化。

var myName = "the global object";var sayHello = function() {    console.log("Hi, my name is " + this.myName);};var myObject = {    myName: "Rebecca"};var secondObject = {    myName: "Colin"};myObject.sayHello = sayHello;secondObject.sayHello = sayHello;sayHello(); //"Hi, my name is the global object"myObject.sayHello(); //"Hi, my name is Rebecca"secondObject.sayHello(); //"Hi, my name is Colin"

還有。不能直接給處於較深的名字空間的函數添加短引用,會導致this變為全域對象,可是能夠對它所處的對象設定短引用。

var myNamespace = {    myObject: {        sayHello: function() {            console.log("Hi, my name is " + this.name);        },        myName: "Rebecca"    }};var hello = myNamespace.myObject.sayHello;hello();    //"Hi, my name is undefined"var obj = myNamespace.myObject;obj.sayHello(); //"Hi, my name is Rebecca"

Tips

call與apply的差別是,apply接收兩個參數:this和函數的參數數組;而call的第一個參數為this,可是後面是函數的參數列表。

本文檔由長沙戴維營教育整理。

Jquery第四課 Javascript中this的使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.