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)
}

~~

posted @ 2017-07-04 18:23  皮皮鲁和鲁西西  阅读(477)  评论(0编辑  收藏  举报