vuejs中 vmode_在VueJS中发现封闭的力量

vuejs中 vmode

By Fabian Hinsenkamp

费边·辛森坎普(Fabian Hinsenkamp)

Today’s frontend technology landscape requires engineers to know about a wide variety of technologies including frameworks, libraries and packages.

当今的前端技术环境要求工程师了解各种技术,包括框架,库和软件包。

No wonder then that vanilla JavaScript skills and in-depth knowledge might start spreading thin. No matter if you are just learning JavaScript, refreshing your basic knowledge or preparing for job interviews → This tutorial is for you!

因此,难怪原始JavaScript技能和深入的知识可能会开始普及。 无论您是在学习JavaScript,刷新基础知识还是为求职面试做好准备→本教程均适合您!

Here you will learn how powerful plain JavaScript closures are. Be aware, this tutorial comes with a challenge. ? It’s all about building an elegant Emoji Picker in VueJS and leveraging closures by using higher order functions.

在这里,您将了解普通JavaScript闭包的强大功能。 请注意,本教程面临挑战。 ? 这一切都是关于在VueJS中构建优雅的Emoji Picker并通过使用高阶函数来利用闭包。

Let’s dive right into it!

让我们开始吧!

功能范围 (Function Scope)

Even though closures are one of the most powerful concepts in JavaScript, they are easily overlooked by many.

尽管闭包是JavaScript中最强大的概念之一,但许多人还是容易忽略它们。

Nevertheless, knowing about closures is fundamental as they define which variables a function has access to during its execution. More precisely, closures define which scopes a function has access to starting from its own, through all parent scopes up to the global scope.

尽管如此,了解闭包是基本的,因为闭包定义函数在执行过程中可以访问哪些变量。 更确切地说,闭包定义了函数可以访问的范围,从它自己的范围开始,直到所有父范围直到全局范围。

To really master closures, it’s essential to have a solid understanding of scopes first. You have probably already experienced the impact of scopes yourself. Every time you execute a function, a scope is created. Whenever you create variables within that function, these are only accessible from within the function itself.

要真正掌握闭包,首先必须对作用域有扎实的了解。 您可能已经亲身经历了示波器的影响。 每次执行函数时,都会创建一个作用域。 每当您在该函数中创建变量时,只能从函数本身内部访问这些变量。

At the time a function is completed (by reaching a return statement or } ) all these variables are destroyed. Next time you execute the function, the same procedure is applied.

在函数完成时(通过return语句或} ),所有这些变量均被销毁。 下次执行该功能时,将应用相同的过程。

Let’s look at the following example to illustrate the concept.

让我们看下面的例子来说明这个概念。

function square(x){
  const squaredX = x  x;
  console.log(squaredX); // 25
  return squaredX;
}

const squaredA = square(5);

console.log(squaredA); // 25 
console.log(squaredX); // ReferenceError: squaredX is not defined

Think about scopes as the temporary context only the code within that function has access to.

将范围视为仅该函数中的代码有权访问的临时上下文。

While scopes have a very limited lifetime, limited by the time a function execution needs to execute, in contrast a function’s closure is already created when a function is initially defined. It also will remain after the execution has been completed.

虽然作用域的生存期非常有限,但受函数执行所需执行时间的限制,相反,在最初定义函数时已经创建了函数的闭包。 执行完成后,它也将保留。

关闭 (Closures)

As mentioned before, closures are responsible for defining which variables are accessible in the scope of a function execution. It’s essential to understand that closures do not provide copies of available variables but references to them. If you are not familiar with JavaScript’s references check out this article.

如前所述,闭包负责定义在函数执行范围内可访问哪些变量。 必须了解闭包不提供可用变量的副本,而是提供对它们的引用。 如果您不熟悉JavaScript的参考,请查看本文

let globalString = 'A'

function hello(){
  const localString = 'C'
  console.log(globalString, localString);
}

hello(); // A C

globalString = "B";

hello(); // B C

The example looks probably very familiar — it’s not anything special. This explains why we barely realise how powerful closures can be, as it’s very common to only define functions in the global scope.

该示例可能看起来非常熟悉-没什么特别的。 这就解释了为什么我们几乎没有意识到闭包有多么强大,因为仅在全局范围内定义函数是很常见的。

However, when functions are defined within another function’s scope, closures enable powerful techniques and patterns. In an object-oriented architecture, closures offer a simple but efficient way to establish data privacy. In more functional architectures, closures are essential to higher order functions and partial application and currying, two more advanced programming techniques.

但是,当在另一个函数的范围内定义函数时,闭包将启用强大的技术和模式。 在面向对象的体系结构中,闭包提供了一种简单而有效的方法来建立数据隐私 。 在功能更强大的体系结构中,闭包对于更高阶的函数以及部分应用程序currying是必不可少的两种更高级的编程技术。

高阶函数 (Higher Order Functions)

A function that operates on other functions, either by taking them as arguments or by returning them, is called a higher-order function.

通过将其他函数作为参数或通过将其返回来对其他函数进行操作的函数称为高阶函数

function createMultiplier(multiplier){
  return function(value){
    return value  multiplier;
  }
}

const multiplyBy2 = createMultiplier(2);

console.log(multiplyBy2(5)); //10

Here we finally can experience the power of closures. Even though createMultiplier has been already successfully completed, we can still access its initial multiplier property.

在这里,我们终于可以体验到封闭的力量。 即使createMultiplier已经成功完成,我们仍然可以访问其初始multiplier属性。

This is possible as closures keep the reference of variables. These can even span over multiple scopes and do not get destroyed when the context terminates. That way, we can still access a specific instance of a local variable.

这是可能的,因为闭包保留了变量的引用。 这些甚至可以跨越多个范围,并且在上下文终止时不会被破坏。 这样,我们仍然可以访问局部变量的特定实例。

资料私隐 (Data Privacy)

function privateVariables(){
  let privateValue = 100;
  return {
    get: function(){
      return privateValue;
    }
  }
}

console.log(privateVariables.get()); //100

How come closures enable us to implement data privacy?

封闭如何使我们实现数据隐私?

We can simply enclose variables and only allow functions within the containing (outer) function scope to access them.

我们可以简单地封装变量,只允许包含(外部)函数范围内的函数访问它们。

You can’t get at the data from an outside scope except through the object’s privileged methods. This pattern also allows us to program to an interface and not the implementation itself.

除了通过对象的特权方法之外,您无法从外部范围获取数据。 这种模式还允许我们对接口进行编程,而不是对实现本身进行编程。

编码挑战:表情符号音色选择器 (Coding Challenge: Emoji Tone Picker)

Great, that’s all the theory we need for actually building something powerful in VueJS and leveraging the power of closures!

太好了,这就是我们实际上需要在VueJS中构建功能强大并利用封闭功能的全部理论!

In fact, higher order functions are the most interesting use case, as we already have a data privacy concept in VueJS.

实际上,高阶函数是最有趣的用例,因为VueJS中已经有了数据隐私概念。

Basically, components already offer an interface through properties and the data object which isn’t accessible from outside.

基本上,组件已经通过属性和数据对象提供了接口,这些接口无法从外部访问。

It is a component to that allows the user to choose the skin tone based an a selection of all available tones, similar to the user experience known from texting on a smart phone.

它是允许用户基于对所有可用色调的选择来选择肤色的组件,类似于从智能手机上发短信所知道的用户体验。

Technically, you should try to create a component that receives a single emoji as props and uses higher order functions to create multiple click event handlers to select different tones.

从技术上讲,您应该尝试创建一个将单个表情符号作为道具并使用高阶函数创建多个单击事件处理程序以选择不同音调的组件。

You can check the sandbox for the code!

您可以在沙箱中查看代码!

暗示 (Hint)

Emojis can be stored as HTML hex codes in string values. The folded hands emoji is &#x1F64F. To change the tone, attach a colour code to it. You can find the codes here.

表情符号可以HTML十六进制代码存储在字符串值中。 双手合十的表情符号是&#x1F64F。 要更改色调,请在其上附加颜色代码。 您可以在此处找到代码。

&#x1F64F + &#x1F3FD = ??

&#x1F64F +&#x1F3FD = ??

建筑挑战扩展 (Building Challenge Extension)

You want to take it one step further, and really see if you mastered closures? Then pass multiple emojis and make it work so you can change the skin tone of multiple emojis one at a time. ?

您想更进一步,真的看看您是否掌握了闭包? 然后传递多个表情符号并使其起作用,以便您可以一次更改多个表情符号的肤色。 ?

结论 (Conclusion)

Closures are the reason why we can access variables of parent scopes while the related functions might have already terminated.

闭包是为什么我们可以在相关功能可能已经终止的情况下访问父范围的变量的原因。

We can use this behaviour of JavaScript in VueJS to dynamically build methods based on dynamic arguments without polluting our components with a vast variety of variables and methods.

我们可以在VueJS中使用JavaScript的这种行为来基于动态参数动态构建方法,而不会用大量的变量和方法来污染我们的组件。

Thanks for reading ?

谢谢阅读 ?



Originally published on my blog at https://hinsencamp.com.

最初发布在我的博客上, 网址https://hinsencamp.com

翻译自: https://www.freecodecamp.org/news/closures-vuejs-higher-order-functions-emojipicker-f10d3c249a12/

vuejs中 vmode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值