• call是什么?一次说个明白


    首先简单粗暴的从例子中看概念

    var a = {};
    function foo() {
      this.name = "hello";
      this.age = 100
    }
    
    foo.call(a)
    

    function bar() {
      this.init()
    }
    var obj = {
      init:function() {
        console.log("hello")
      }
    }
    bar.call(obj) //hello
    

    通过以上两个例子我们发现call可以干什么?

    • 调用call() 传递的参数中的函数和属性
    • 定义call() 传递的参数中的函数和属性

    为什么call 可以调用 定义 别人的属性和方法?举个例子 a.call(b)

    1. 函数a被执行
    2. a中的this被指向b,a要用的属性或方法可以从b中拿,b没有的可以在a中this.xxx=xxx 自己去定义。

    感觉有点蒙?没关系我画了几张图帮助理解

    准确的说a与b是通过call建立起来的引用关系!我们知道JS分为基本类型和引用类型(不知道的可以百度一下,肚子饿了不想写了)

      var myApp = myApp || {};
    myApp.utils =  {};
    (function () {
      var val = 5;
      this.getValue = function () {
          return val;
      };
       
      this.setValue = function( newVal ) {
          val = newVal;
      }
          
      // also introduce a new sub-namespace
      this.tools = {};
        
    }).apply( myApp.utils );
    
    
    

    function Foo() {
    return {}
    }

    var foo = new Foo()
    foo.age = 100;
    foo.getAge = function() {
    console.log(this.age)
    }

    ~~

  • 相关阅读:
    *Delete Duplicate Emails
    Rising Temperature [MySQL]
    mysql链接表,connection string, federated engine
    谷歌在招什么样的人?
    用memcached的时候找key找不到,写了个命令来找找
    jna
    绕树三匝,无枝可依
    vm lxc
    linux proxy
    elisp
  • 原文地址:https://www.cnblogs.com/shigongzi/p/7117977.html
Copyright © 2020-2023  润新知