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()可以让括号里的对象来继承括号外函数的属性。

     

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

  • 相关阅读:
    谁在TDD
    开源许可证简单总结
    【转】IIS HTTP500错误以及COM+应用程序8004e00f错误的解决方法
    [原]Linux平台Boost的编译方法
    [原]linux下格式化磁盘的相关问题
    [原]编译MongoDB,C++连接MongoDB测试
    [转]谈谈Unicode编码,简要解释UCS、UTF、BMP、BOM等名词(科普)
    [转]linux下如何查看文件编码格式及转换文件编码
    [原]linux(虚拟机)下安装MySQL
    [转]Linux下比较全面的监控工具dstat
  • 原文地址:https://www.cnblogs.com/liumcb/p/13680188.html
Copyright © 2011-2022 走看看