Function.prototype.call
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
使ç¨çµ¦å®ç this 忏以ååå¥çµ¦å®ç忏ä¾å¼å«æå彿¸
åè¨»ï¼æ¤å½æ¸çææèªæ³å¤§è´ä¸è apply() ç¸åï¼ä»ååºæ¬ä¸ä¸åèåªæ call() æ¥åä¸é£ä¸²ç忏ï¼è apply() å®ä¸ç array ä½çºåæ¸
| Function ç©ä»¶çæ¹æ³ | |
|---|---|
| è¢«å¯¦ä½æ¼ | JavaScript 1.3 |
| ECMAScript çæ¬ | ECMAScript 第ä¸ç |
èªæ³
fun.call(thisArg[, arg1[, arg2[, ...]]])
忏
thisArg-
å¼å«*
fun*ææä¾çthiså¼ã 注æï¼å®å¯è½æ¯ä¸åç¡æ³å¨å½æ¸å §çå°çå¼ï¼è¥éå彿¸æ¯å¨éå´è模å¼( non-strict mode ),nullãundefinedå°æè¢«ç½®ææå ¨åè®æ¸ï¼èåçåæ çå¼å°æè¢«å°è£ arg1, arg2, ...-
å ¶ä»åæ¸
æè¿°
ä½ å¯ä»¥å¨å¼å«ä¸åç¾åç彿¸æï¼ä½¿ç¨ä¸ä¸æ¨£ç this ç©ä»¶ãthis æåç
§å°ç®åçç©ä»¶ï¼å¼å«çç©ä»¶ä¸
ä½¿ç¨ callï¼ä½ å¯ä»¥å¯¦ä½å½æ¸ä¸æ¬¡ï¼ç¶å¾å¨å
¶ä»çç©ä»¶ä¸ç´æ¥ç¹¼æ¿å®ï¼èä¸ç¨å¨æ°çç©ä»¶ä¸éå¯«è©²å½æ¸
ç¯ä¾
>ä½¿ç¨ call ä¾ä¸²æ¥ç©ä»¶ä¸ç建æ§å
ä½ å¯ä»¥ä½¿ç¨ call ä¾ä¸²æ¥å
¶ä»ç©ä»¶ç建æ§åï¼å°±å Javaãä¸é¢çä¾åä¸ï¼Product ç©ä»¶ç建æ§åå®ç¾©äºå
©å忏 name 以å priceãå
¶ä»å½æ¸ Food å Toy å¼ç¨äº Product 並å³å
¥ thisãname å priceãProduct åå§åå®çå±¬æ§ name å priceï¼èå
©åå彿¸åå®ç¾©äº categoryã
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError(
'Cannot create product "' + name + '" with a negative price',
);
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = "food";
}
Food.prototype = new Product();
function Toy(name, price) {
Product.call(this, name, price);
this.category = "toy";
}
Toy.prototype = new Product();
var cheese = new Food("feta", 5);
var fun = new Toy("robot", 40);
ä½¿ç¨ call ä¾å¼å«å¿åç彿¸
ä¸é¢éåç°¡æçä¾åä¸ï¼æååäºä¸åå¿åç彿¸ï¼ä¸¦ç¨ call ä¾è®å®æç¨å¨æ¯åå¨ä¸²åä¸çç©ä»¶ä¸. éåå¿å彿¸ç主è¦ç¨éæ¯å å
¥ä¸å print 彿¸å°æ¯åç©ä»¶ä¸ï¼éå彿¸å¯ä»¥å°åºæ¯åç©ä»¶ç index ææ¨ã å³å
¥ç©ä»¶ä½çº this çå¼ä¸¦ä¸æ¯å¿
è¦çï¼ä½ä»æè§£éçç¨éã
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);
}
è¦ç¯
| Specification |
|---|
| ECMAScript® 2027 Language Specification> # sec-function.prototype.call> |