淺談JavaScript--this指向

來源:互聯網
上載者:User

標籤:define   status   函數   post   包括   參數   淺談   efi   java   

js中this的值取決於調用的模式

  • 方法調用模式
var student={    name:"adoctors",    showThis:function(){        console.log(this);          //此處this為整個student對象,包括其中的屬性和方法        console.log(this.name);   // ‘adoctors‘    }}
  • 函數調用模式
function fn(){    console.log(this);   //this指向window對象        var name = "adoctors";    console.log(this.name);   //undefined        //也可通過賦值變數改變this指向    var that=this;    ···}
  • 構造器調用模式
var fn = function (status){    this.status = status;}fn.prototype.get_status = function(){    return this.status;}var test = new fn(‘my status‘);console.log(test.get_status);   //my status,this指向test 
  • apply和call調用模式
function foo(){    console.log(this.fruit);}// 定義一個全域變數,等同於window.fruit = "banana";var fruit = "banana";var  o = {    fruit : "apple"};    foo.apply(window);  // "banana";foo.call(o);  // "apple";

apply和call的唯一區別,就是在傳參的時候,apply的參數需要放在一個數組裡面,而call不需要;

淺談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.