js---13 this call apply

來源:互聯網
上載者:User

標籤:pre   app   記憶體   bsp   中括弧   print   dom   傳遞   instance   

<script type="text/javascript">//this:this可以寫在js全劇環境中(全域環境中this是window對象),this可以寫在函數中,可以寫在對象中,function f(){     this.name = "asdfas";}var o ={    name :"cj",     print:function(){        console.log(this.name);    }};o.print();//cjvar f = o.print();//java的記憶體分析模型來分析js記憶體模型。函數是函數對象,f就指向print指向的函數對象,f();//undefined,/*this是運行時決定不是代碼寫的時候決定,this寫在函數中,哪個對象調用函數,這個對象就看成這個函數類的執行個體化對象,this就指向那個對象,  f() === window.f(),所以未定義。*/var ele = document.getElementById("id");ele.addEventListener("click",function(){    console.log(this);//this永遠指向dom元素,就是引發事件的對象,})//call,apply都是函數對象有的,動態改變函數調用的對象function log(a){    console.log(this[a]);}log("name");  //this是window對象,globallog.call(o,"name");//cj,相當於o.log("name"),不讓window調用log函數讓o來調用log函數,call方法第一個參數是要調用這個函數的對象,第二個是參數。function log(a,b){     console.log(this[a]);//通過中括弧訪問函數對象的成員屬性,     console.log(this[b]);}log("name","");log.apply(o,"name","age");log.apply(o,["name","age"]); //apply接受參數是數組,call是一個一個傳遞log.call(this,)  == this.log()function p(){    this.name = "111";//函數的this是調用這個函數的對象}var o ={};p.call(o);//相當於o.p(),調用函數看成是類的構造器執行了,那麼此時o就是函數這類的執行個體化對象,就有了這個類的屬性了,this就指向o,console.log(o.name); // 111  function Person(name,age){      this.name =  name;      this.age = age;  }  var p1  = new Person   ("cj",22);//new出來的,當然p1就是這個函數類的執行個體化對象  console.log(p1 instanceof Person); //true  //自訂new   function New(f){ //f 是個函數。f 構造器函數      var o = {"__proto__":f.prototype}; //o.__proto__ 指向函數f的prototype      return function(){//返回函數,可以不寫形參,          //o.name = arguments[0];        //o.age = arguments[1];          f.apply(o,arguments);//o調用f,類的構造器執行,那麼o就是函數f的執行個體化對象了,就有了這個類的屬性和值                    return o;//函數執行時返回o對象      }  }  var p2 = New(Person)("xx",33);//New(Person)返回函數,("xx",33)函數執行返回o  console.log(p2.name);//xx  console.log(p2 instanceof Person);//true</script>

 

js---13 this call apply

聯繫我們

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