是 init.apply 和 methods[method].apply javascript 行是默认的

Is the init.apply and methods[method].apply javascript lines are by default

本文关键字:apply javascript 默认 init methods method      更新时间:2023-09-26

我正在尝试学习jquery插件,在这个过程中我试图先理解一些jquery插件。 我读过几个插件,在插件的开头遇到了几个常见的代码旋转网。

if (methods[method]) {
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
 } else if (typeof method === 'object' || !method) {
     return methods.init.apply(this, arguments);
 } else {
     $.error('Method ' + method + ' does not exist on jQuery.jModalbox');
 }

谁能告诉我,

  1. 是不是像,我们在构建插件时必须遵循这个
  2. 我观察到控制台不会来

    return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));

    那么为什么我们需要 if 部分。

  3. 为什么使用 Apply 调用方法 init,我的意思是 为什么像 : methods.init.apply(this, arguments); 为什么不喜欢这样:methods.init(arguments);
  4. 我遇到过阅读这个 apply() ,但不清楚。 请任何机构解释

这很难解释,但我会尽力而为。

如您所知apply该方法需要 2 个参数。 首先,context of function,第二,array of function parameters

context就像一个对象自我的引用,我们可以称之为function scope。它指的是功能中的this

您显示的此代码必须使用 apply 方法,因为他们想要设置被调用函数context。我真的很确定调用的函数this用于做某事。

如果您直接调用函数,它将没有对您想要this的引用。这就是为什么他们必须使用apply而不是直接调用的原因。

希望这有帮助!

有关更多信息,您可以阅读此内容