javascript中的call(),apply(),bind()

javascript中的call(),apply(),bind()

九月 18, 2020

javascript中的call(),apply(),bind() 未完

参考资料

  1. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
  2. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
  3. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  4. https://www.runoob.com/w3cnote/js-call-apply-bind.html
  5. https://www.zhihu.com/question/20289071
  6. https://www.jb51.net/article/194222.htm

正篇

call()``apply()``bind()方法都是在Function中的,所以都是跟在方法后使用的

call()

call()方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。举个例子吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function Product(name, price) {
this.name = name;
this.price = price;
}

function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"

或者

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);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
以下引用知乎中的回答
本身不难理解,看下MDN就知道了,但是不常用,遇到了,还要脑回路回转下。或者时间长了,还是要确定下去看下文档,为了方便记忆:

猫吃鱼,狗吃肉,奥特曼打小怪兽。

有天狗想吃鱼了

猫.吃鱼.call(狗,鱼)

狗就吃到鱼了

猫成精了,想打怪兽

奥特曼.打小怪兽.call(猫,小怪兽)

至于能在哪里应用?我琢磨了下,除了参考资料中的例子能提高复用之外

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function Food(name) {
this.name = name || "null";
this.category = 'food';
this.what = function(){
console.log("This is " + this.category);
}
this.eat = function(){
console.log("I would like to eat " + this.name);
}
return this;
}

function Weapon(name) {
this.name = name || "null";
this.category = 'weapon';
this.what = function(){
console.log("This is " + this.category);
}
this.attack = function(){
console.log("I will attack you with " + this.name);
}
return this;
}

Food.call(Weapon(), "Sword").attack()
// I will attack you with Sword

或者是这样?

1
2
3
4
5
6
7
8
9
10
11
12
13
function Food(name) {
this.name = name || "null";
console.log("I would like to eat " + this.name);
}

function Weapon(name) {
this.name = name || "null";
console.log("I will attack you with " + this.name)
}

Food.call(Weapon(), "Sword")
// I will attack you with null
// I would like to eat Sword

由于我基本没有开发经验,所以还请各位大佬指教

apply()