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

     

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

  • 相关阅读:
    面向对象程序设计简介(1/2)
    iOS官方Sample大全
    AFN不支持 "text/html" 的数据的问题:unacceptable content-type: text/html
    谈ObjC对象的两段构造模式
    关于self和super在oc中的疑惑与分析 (self= [super init])
    在Xcode中使用Git进行源码版本控制
    NSObject之二
    NSObject之一
    Objective-C Runtime 运行时之六:拾遗
    Objective-C Runtime 运行时之五:协议与分类
  • 原文地址:https://www.cnblogs.com/liumcb/p/13680188.html
Copyright © 2011-2022 走看看