js-apply call bind 浅析

call
1.第一个参数指定了this,第二个参数传给this,也就是call前面的函数,作为他的参数第三个参数也一样

指定了this,就是执行环境,greet的this在i里面找

function
greet() { var reply = [this.person, 'Is An Awesome', this.role].join(' '); console.log(reply); } var i = { person: 'Douglas Crockford', role: 'Javascript Developer' }; greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer

第二个参数传给this,也就是call前面的函数,也就是函数继承,知乎大佬这莫说

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

有天狗想吃鱼了

猫.吃鱼.call(狗,鱼)

狗就吃到鱼了

猫成精了,想打怪兽

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


function Product(name, price) { this.name = name; this.price = price; } function Food(name, price) { Product.call(this, name, price); this.category = 'food'; } //等同于 function Food(name, price) { this.name = name; this.price = price; if (price < 0) { throw RangeError( 'Cannot create product ' + this.name + ' with a negative price' ); } this.category = 'food'; } //function Toy 同上 function Toy(name, price) { Product.call(this, name, price); this.category = 'toy'; } var cheese = new Food('feta', 5); var fun = new Toy('robot', 40);

2.使用call方法调用匿名函数

1.写一个匿名函数

2.给数组中每一个元素作为this去执行这个匿名函数,就是this在animals[i]里面找,并把i传里面

3.因为是匿名函数,没有函数名,所以有this.print()

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);
}

 2.call 和 apply 一模一样几乎

区别只在于传递参数的方式
console.log.apply(console, [1, 2, 3, 4])
console.log.call(console, 1, 2, 3, 4)
}

3.bind最大用途在于指定this的值,第二个参数是提前给他穿进去了这个参数

function list() {
  return Array.prototype.slice.call(arguments);//把arguments变成数组,再使用数组才有的slice方法
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

  

猜你喜欢

转载自www.cnblogs.com/xiaobai1/p/9031791.html
今日推荐