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

     

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

  • 相关阅读:
    zabbix 设备(自己的实践)
    10.24的注意事项——解决linux_jni编译错误的问题
    [Angular] Adding keyboard events to our control value accessor component
    [tmux] Copy and paste text from a tmux session
    [tmux] Customize tmux with tmux.conf
    [tmux] Zoom and resize to view a particular pane within tmux
    [tmux] Manage terminal workspaces using session naming
    [tmux] Reuse terminal workspaces using tmux sessions
    [tmux] Create collections of panes using tmux windows
    [tmux] Organize your terminal using tmux panes
  • 原文地址:https://www.cnblogs.com/liumcb/p/13680188.html
Copyright © 2011-2022 走看看