资讯专栏INFORMATION COLUMN

Brief introduction of how to 'Call, Apply and

incredible / 623人阅读

摘要:关于在绝大多数情况下,函数的调用方式决定了的值。不能在执行期间被赋值,并且在每次函数被调用时的值也可能会不同。它们除了参数略有不同,其功能完全一样。它们的第一个参数都为将要指向的对象。

关于 this

在绝大多数情况下,函数的调用方式决定了this的值。this不能在执行期间被赋值,并且在每次函数被调用时this的值也可能会不同。

全局 this
window.something = "I love JavaScript"
console.log(this.something) // "I love JavaScript"
console.log(window === this) // true
调用全局 function
var a = 1
function test() { console.log(this.a) }
test() // 1 - still remains the window reference
调用对象中的 function
this.a = "I am in the global scope"
function Test() {
  this.a = "I am in the test scope"
  this.show = function() { console.log(this.a) }
}
Test.prototype.display = function () { console.log(this.a) }
var test = new Test() // updated the scope of this
test.show() // I am in the test scope
test.display() // I am in the test scope 
关于 call / apply

JavaScript 内部提供了一种机制,让我们可以自行手动设置 this 的指向。它们就是 call 与 apply。所有的函数都具有着两个方法。它们除了参数略有不同,其功能完全一样。它们的第一个参数都为 this 将要指向的对象。

一个最简单的继承
function Laptop(name, storage) {
  this.name = name
  this.storage = storage
}

function Dell(name, storage, company) {
  Laptop.call(this, "Dell", 1024)
  this.company = company
}

console.log(new Dell("Dell", 1024, "Dell Inc").storage)
改变 this
var obj = {
  entry: "mammals-banana-tower",
  duration: 0
}

function breed(name) {
  console.log("Show this breeding info", name, this.entry, this.duration)
  console.log(this === obj)
}

breed() // this => window
breed.call(obj, "Frank") // this => obj

注:当没有传递任何参数作为 call() 的第一个参数时,在非严格模式下,this 会指向 window。

实现一个简单的 call
var _call = function (that) {
  that = that ? Object(that) : window
  that.func = this

  function formatArgs(oArgs, sign) {
    var _args
    for (var i = 1, len = oArgs.length; i < len; i++) {
      _args.push(sign ? ("_param_" + i) : oArgs[i])
    }
    return _args
  }

  var args = formatArgs(arguments)
  var newFunc = (new Function("args", "return that.func(" + formatArgs(args, true).toString() + ")"))(args)

  that.func = null
  return newFunc
}
关于 bind () => {} 和 bind this

用过 React 的同学都知道,当使用 class component 时,需要在 constructor 绑定当前的成员函数,或者针对事件委托的情况下,也需要进行绑定;ES6 箭头函数可以让我们更专注于具体的实现逻辑,简化了 this 操作

// ES5
// 
// constructor() { this.handleClick = this.handleClick.bind(this) }

// ES6
//  handleClick()}>
// handleClick = () => {}
无效的 re-bound
var f = function() { console.log(this.text) }
f = f.bind({ text: "I was bound" }).bind({ text: "I won"t be bound" })
f() // I was bound

很容易发现,f.bind() 返回的绑定函数对象仅在创建是保留当前的上下文(或者传入的参数),因此无法在第二次进行重绑定。

一个相对完善的 bind
var _bind = function (that) {

  var fBound,
    target = this,
    slice = Array.prototype.slice,
    toStr = Object.prototype.toString,
    args = slice.call(arguments, 1); // except that

  if (typeof target !== "function" || toStr.call(target) !== "[object Function]") {
    throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  }

  var binder = function () {
    var oArgs = args.concat(slice.call(arguments))
    if (this instanceof fBound) {
      var result = target.apply(this, oArgs);
      return Object(result) === result ? result : this;
    } else {
      return target.apply(that, oArgs);
    }
  };

  var i = 0,
    params = [],
    paramLength = Math.max(0, target.length - args.length);

  for (; i < paramLength; i++) {
    params.push("_param_" + i);
  }

  fBound = (new Function(
    "binder",
    "return function(" + params.join(",") + ") { return binder.apply(this,arguments); }"
  ))(binder);

  // maintain the reference of prototype
  if (target.prototype) {
    var fNOP = function () { };
    fNOP.prototype = target.prototype;
    fBound.prototype = new fNOP();
    fNOP.prototype = null;
  }

  return fBound;
};
参考

https://developer.mozilla.org...
https://developer.mozilla.org...
https://developer.mozilla.org...
https://developer.mozilla.org...
https://developer.mozilla.org...
https://developer.mozilla.org...
https://www.ecma-internationa...
https://javascript.info/bind
https://juejin.im/post/5c0605...
https://github.com/mqyqingfen...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/101985.html

相关文章

  • SegmentFault Live Q & A & Streaming Guide

    CHANGELOG: 中文版本看这里 2017-03-14 [adjustment] change the procedure of the application for being a lecturer [adjustment] change the way of how to start or end the live 2017-03-22 [new] some details a...

    mochixuan 评论0 收藏0
  • A Brief Introduce of Database Index(索引简介)

    摘要:所以这篇文章希望帮助大家理解一下。我没有在算法上展开太多,因为很多算法相似,如果展开容易喧宾夺主。等过段时间我会加入一些实验数据和代码进这篇文章,最近比较懒不想安装数据库安装实在太烦了。 这是我写的一篇研究生申请的writing sample,关于数据库索引的,对关系型数据库的索引从数据结构到用途再到作用对象简单分析了一下,因为我发现在实际工作中,index是个好东西,但是很多DBA并...

    luqiuwen 评论0 收藏0
  • A Brief Introduce of Database Index(索引简介)

    摘要:所以这篇文章希望帮助大家理解一下。我没有在算法上展开太多,因为很多算法相似,如果展开容易喧宾夺主。等过段时间我会加入一些实验数据和代码进这篇文章,最近比较懒不想安装数据库安装实在太烦了。 这是我写的一篇研究生申请的writing sample,关于数据库索引的,对关系型数据库的索引从数据结构到用途再到作用对象简单分析了一下,因为我发现在实际工作中,index是个好东西,但是很多DBA并...

    marek 评论0 收藏0
  • 《You Don&#039;t Know JS》阅读理解——this

    摘要:运行规则根据的运作原理,我们可以看到,的值和调用栈通过哪些函数的调用运行到调用当前函数的过程以及如何被调用有关。 1. this的诞生 假设我们有一个speak函数,通过this的运行机制,当使用不同的方法调用它时,我们可以灵活的输出不同的name。 var me = {name: me}; function speak() { console.log(this.name); }...

    tianren124 评论0 收藏0
  • the deadline of JavaScript&#039;s this

    摘要:在用处千千万,基于自己研究和认识,今天做一个了断。可以取所属对象的上下文的方法称为公共方法,可以使属性,方法变成公开的属性方法在构造函数,方法中用到。内部函数调用的时候,只能搜索到其活动对象为止,不可能直接访问外部函数中的变量。 this this在JavaScript用处千千万,基于自己研究和认识,今天做一个了断。 全局,匿名函数调用 对象方法调用 闭包总指向上一级 构造函数中,指...

    chinafgj 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<