call

我又双叒忘记了 call 作用

  那个函数调用 call,哪个函数就会执行,而在 call 方法后面接参数的话,这个参数对象会作为函数的 this 对象,如果不添加参数,则默认 this 为 window【A】,实际上,如果是直接调用, this 也默认是 window【B、B1】。
  如果函数中,有为 this 对象添加属性,即 this.a = 4,则call 方法中的参数所有者就会被设置有 a 属性【C】。

  call 只是将(调用)所有者作为 this 对象而已,并不使得所有者即对象参数拥有这个函数,不要混淆会变成对象字面量形式,也就是 obj.Func(),不会存在。

function Func() {
    this.a = 4;
    this.b = 5;
    return this.a + this.b;
  }

  console.log('情况 【B】 ');
  Func();
  console.log(window.b); // 5

  console.log('情况 【B1】')
  function funcOut() {
    this.a = 6;
    this.b = 8;
    console.log(Func()); // 8
  }
  funcOut();

  console.log('情况 【A】');
  Func.call();
  console.log(window.a); // 4

  console.log('情况 【C】');
  const obj = {};
  console.log(Func.call(obj)); // 9

  console.log('情况 【D】');
  console.log(obj.a); // 4
  console.log(obj.b); // 5
  console.log(obj); // {a: 4, b: 5} 没有 Func 方法属性哦
example1

 

通过 call ,可以使得 Generator 函数像普通函数一样使用,如可以变成构造函数,执行 new 命令:

  一个对象具有的属性和方法可以通过该对象的 prototype 寻找,所以当为对象的 prototype 对象添加属性时,这时,对象实例也会有这个属性。

  Generator 函数对象 gen 的实例是 gen(),当实例调用 call,并调用 gen 的 prototype 作为所有者时,则 Generator 函数对象也会具有 a、b、c 属性,则它的实例对象也同样具有(通过原型链)。

function* gen() {
  this.a = 1;
  yield this.b = 2;
  yield this.c = 3;
}

let iterObj = gen.call(gen.prototype);
console.log(iterObj.next()); // {value: 2, done: false}
console.log(iterObj.next()); // {value: 3, done: false}
console.log(iterObj.next()); // {value: undefined, done: true}

console.log(iterObj.a); // 1
console.log(iterObj.b); // 2
console.log(iterObj.c); // 3
example2
function* gen() {
  this.a = 1;
  yield this.b = 2;
  yield this.c = 3;
}

function F() {
  return gen.call(gen.prototype);
}

var obj = new F();
console.log(obj.next()); // {value: 2, done: false}
console.log(obj.next()); // {value: 3, done: false}
console.log(obj.next()); // {value: undefined, done: true}

console.log(obj.a); // 1
console.log(obj.b); // 2
console.log(obj.c); // 3
example3
<script>
  /*
  使用 call 方法调用函数并且指定上下文的 'this'
  让我比较深刻的理解是 call 的第一个参数将作为(替代)函数里面 this 对象,call 后面的参数将作为函数参数, 如 (function(){}).call(animals[i], i)。
  使用 call 方法调用函数并且不指定第一个参数,如 display.call();
  * */
  var animals = [
    { species: 'Lion', name: 'kind' },
    { 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);
  }
  /*
  打印
    #0 Lion: kind
    #1 Whale: fail
  */

  var sData ='Wisen';
  function display () {
    console.log('sData value is %s ', this.sData);
  }
  display.call();
  /*
  打印
    sData value is Wisen
  */
</script>
example4

 

posted @ 2022-05-23 10:20  し7709  阅读(625)  评论(0)    收藏  举报