call和apply(學習筆記)

來源:互聯網
上載者:User

標籤:his   int   price   data   屬性   因此   數組   方法   技術   

call文法:

function.call(thisArg, arg1, arg2, ...)

參數:

thisArg:可選的。表示this修改後指向色目標。(注意:如果該方法是在非strict 模式下的函數,那麼null和未定義將被全域對象替換,而原始值將被轉換為對象。)

arg1:,arg2可選的。表示函數的參數列表,表示哪些函數的屬性會繼承過去。

例子:

function Product(name, price) {  this.name = name;  this.price = price;}function Food(name, price) {  Product.call(this, name, price);  this.category = ‘food‘;}function Toy(name, price) {  Product.call(this, name, price);  this.category = ‘toy‘;}var cheese = new Food(‘feta‘, 5);var fun = new Toy(‘robot‘, 40);

其他例子:

對匿名函數上使用call

var animals = [  { species: ‘Lion‘, name: ‘King‘ },  { species: ‘Whale‘, name: ‘Fail‘ }];for (var i = 0; i < animals.length; i++) {  (function(i) {    this.print = function() {      console.log(‘#‘ + i + ‘ ‘ + this.species                  + ‘: ‘ + this.name);    }    this.print();  }).call(animals[i], i);}
匿名函數使用calld代碼

使用調用函數來為this指定上下文

 1 function greet() { 2   var reply = [this.person, ‘Is An Awesome‘, this.role].join(‘ ‘); 3   console.log(reply); 4 } 5  6 var i = { 7   person: ‘Douglas Crockford‘, role: ‘Javascript Developer‘ 8 }; 9 10 greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
調用函數為this指定上下文代碼

調用函數不指定參數(參考文中開頭對參數的描述)

1 var sData = ‘Wisen‘;2             3 function display(){4     console.log(‘sData value is %s ‘, this.sData);5 }6 7 display.call(); //sData value is Wisen
不指定參數

 call和apply的區別只是.call(this,arg1,arg2,...)是參數列表.aoply(this,[arg1,arg2,...])是參數數組,因此不再介紹。

bind文法:

再說,吃飯了

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.