zoukankan      html  css  js  c++  java
  • JavaScript中的call和apply的用法?

    call的用法:

    1.修改this指向

    obj = {
      name:'liumcb'
    }
    function func() {
        console.log(this); 
    }
    func();     ------- 指向window
    func.call(obj);   --------指向obj

    2.借用别的对象的方法:

      var Person1 = function () {
        this.name = 'linxin';
      }
      var Person2 = function () {
        this.getname = function () {
          console.log(this.name);
        }
        console.log('this===', this);  ------ 指向 Person2 {getname: ƒ}
        Person1.call(this);  ------ 作用:使用 Person1 对象代替 this 对象
      }
      var person = new Person2();
      console.log('person===', person);   ---- Person2 {name: "linxin", getname: ƒ}
      person.getname();

    在Person1.call(this): 使用 Person1 对象代替 this 对象, 那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。

    3.调用函数

    function func() {
        console.log('linxin');
    }
    func.call();            // linxin

    apply、call 方法都会使函数立即执行,因此它们也可以用来调用函数。

     

    ------------恢复内容开始------------

    call的用法:

    1.修改this指向

    obj = {
      name:'liumcb'
    }
    function func() {
        console.log(this); 
    }
    func();     ------- 指向window
    func.call(obj);   --------指向obj

    2.借用别的对象的方法:

      var Person1 = function () {
        this.name = 'linxin';
      }
      var Person2 = function () {
        this.getname = function () {
          console.log(this.name);
        }
        console.log('this===', this);  ------ 指向 Person2 {getname: ƒ}
        Person1.call(this);  ------ 作用:使用 Person1 对象代替 this 对象
      }
      var person = new Person2();
      console.log('person===', person);   ---- Person2 {name: "linxin", getname: ƒ}
      person.getname();

    在Person1.call(this): 使用 Person1 对象代替 this 对象, 那么 Person2 就有了 Person1 中的所有属性和方法了,相当于 Person2 继承了 Person1 的属性和方法。

    3.调用函数

    function func() {
        console.log('linxin');
    }
    func.call();            // linxin

    apply、call 方法都会使函数立即执行,因此它们也可以用来调用函数。

    简而意之:就是 A.call(B),call()可以让括号里的对象来继承括号外函数的属性。

     

    ------------恢复内容结束------------

  • 相关阅读:
    1722 最优乘车 1997年NOI全国竞赛
    5969 [AK]刻录光盘
    tarjan算法讲解
    求有向图的强连通分量个数 之 Kosaraju算法
    信使
    1405 奶牛的旅行
    P1828 香甜的黄油 Sweet Butter
    洛谷P2235 [HNOI2002]Kathy函数
    「BZOJ1010」[HNOI2008] 玩具装箱toy(斜率优化)
    BZOJ 1974 [Sdoi2010] auction 代码拍卖会(数位dp)
  • 原文地址:https://www.cnblogs.com/liumcb/p/13680188.html
Copyright © 2011-2022 走看看