在JavaScript中,当上下文已由谁调用时确定了为什么将上下文作为参数传递给函数调用?

问题描述 投票:0回答:1

阅读了有关Medium的一篇文章,>]

您必须了解bitfish的这14个JavaScript函数

在本文中,作者撰写了关于JavaScript开发人员在面试时/之前必须知道或理解的功能-以便担任JavaScript开发人员的职位。

在这些示例中,不断地使用上下文作为可选参数。不幸的是,作者没有详细说明为什么我们要传递如下上下文参数:

mappedArr[i] = fn.call(context, arr[i], i, this); 

我的问题是“在JavaScript中,当上下文已经由谁调用时确定了为什么将上下文作为参数传递给函数调用?”

在什么条件下使该上下文可用(另一个上下文)有用?

这里是下面列出的代码:

let selfMap = function(fn, context) {

   let arr = Array.prototype.slice.call(this);
   let mappedArr = Array();
   for(let i=0; i < arr.length; i++) {

     if (! arr.hasOwnProperty(i)) continue;

     let info = [];
     info.push({ "context" : context } );
     info.push({ "arr[i]" : arr[i] } );
     info.push({ "i" : i } );
     info.push({ "this" : this } );
     console.log(info);

     mappedArr[i] = fn.call(context, arr[i], i, this); 

   } 
   return mappedArr;

 }; 

然后使用:

Array.prototype. selfMap = selfMap;
[1,2,3].myMap(n => n * 2);

为什么要提供上下文作为myMap的第二个参数?我认为可能存在JavaScript设计模式,但由于与Google搜索无关的所有搜索结果碎片,目前我找不到任何参考。

我确实编写了一个函数并作为第二个参数传入上下文,但是我不确定,虽然我可以提出自己的想法,但这样做的主要原因是什么?

这是我使用它的示例:

[1,2,3].selfMap((n, o, p) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "p" : p } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

});

可以通过此窗口或窗口或{}

上下文等于我们从中调用方法的当前上下文

[1,2,3].selfMap((n, o, context) => {

         let info = [];
         info.push({ "n" : n } );
         info.push({ "o" : o } );
         info.push({ "context" : context } );
         info.push({ "this" : this } );
         console.log(info)
         return n * 2;

}, this);

窗口作为上下文参数

[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, window);

并且我们可以使用自定义对象

[1,2,3].selfMap((n, o, context) => {

     let info = [];
     info.push({ "n" : n } );
     info.push({ "o" : o } );
     info.push({ "context" : context } );
     info.push({ "this" : this } );
     console.log(info)
     return n * 2;

}, { something: 1 });

所以,我知道可以传递上下文,但是我不知道为什么要传递上下文。

请在您的回答中提供不仅是解释,而且还提供示例以澄清您的解释。

谢谢

[阅读有关bitmedia的文章,您必须了解这14种JavaScript函数的文章,作者撰写了有关JavaScript开发人员必须知道或理解的函数的文章...

javascript design-patterns this
1个回答
0
投票

在某些情况下,调用者可能会遮盖上下文(this),但是可能需要完全引用另一种上下文。在这种情况下,如果将上下文作为参数传递,将非常有帮助。

请考虑以下示例

© www.soinside.com 2019 - 2024. All rights reserved.