標籤: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(學習筆記)