javascript关键字_删除JavaScript的“ this”关键字使其成为一种更好的语言。 这就是为什么。...

javascript关键字

Read Functional Architecture with React and Redux and learn how to build apps in function style.

阅读具有React和Redux的功能架构,并学习如何以函数样式构建应用程序。

this is of course the source of much confusion in JavaScript. The reason being that this depends on how the function was invoked, not where the function was defined.

this当然是JavaScript引起很多混乱的根源。 原因是this取决于函数的调用方式,而不取决于函数的定义位置。

JavaScript without this looks like a better functional programming language.

没有this功能JavaScript看起来是一种更好的功能编程语言。

这种失落的环境 (this losing context)

Methods are functions that are stored in objects. In order for a function to know on which object to work, this is used. this represents the function’s context.

方法是存储在对象中的函数。 为了让函数知道哪个对象上下工夫, this被使用。 this代表了函数的上下文。

this loses context in many situations. It loses context inside nested functions, it loses context in callbacks.

在许多情况下this会失去上下文。 它会丢失嵌套函数内的上下文,会丢失回调中的上下文。

Let’s take the case of a timer object. The timer objects waits for the previous call to finish before making a new call. It implements the recursive setTimeout pattern. In the next example, in nested functions and callbacks, this loses context:

让我们以一个计时器对象为例。 计时器对象等待上一个调用完成,然后再发起新调用。 它实现了递归setTimeout模式。 在下一个示例中 ,在嵌套函数和回调中, this会丢失上下文:

class Timer {
 constructor(callback, interval){
    this.callback = callback;
    this.interval = interval;
    this.timerId = 0;
  }
  
 executeAndStartTimer(){
   this.callback().then(function startNewTimer(){
       this.timerId =  
       setTimeout(this.executeAndStartTimer, this.interval);
   });
 }
    
 start(){
   if(this.timerId === 0){
     this.executeAndStartTimer();
   }
 }
 stop(){
   if(this.timerId !== 0){
     clearTimeout(this.timerId);
     this.timerId = 0;
   }
 }
}

const timer = new Timer(getTodos, 2000);
timer.start();
function getTodos(){
  console.log("call");
  return fetch("https://jsonplaceholder.typicode.com/todos");
}

this loses context when the method is used as an event handler. Let’s take the case of a React component that builds a search query. In both methods, used as event handlers, this loses context:

当该方法用作事件处理程序时, this会丢失上下文。 让我们以构建搜索查询的React组件为例。 在这两种用作事件处理程序的方法中, this会丢失上下文:

class SearchForm extends React.Component {
  handleChange(event) {
    const newQuery = Object.freeze({ text: event.target.value });
    this.setState(newQuery);
  }
  search() {
    const newQuery = Object.freeze({ text: this.state.text });
    if (this.props.onSearch) this.props.onSearch(newQuery);
  }
  render() {
    return (
      <form>
      <input onChange={this.handleChange} value={this.state.text} />
      <button onClick={this.search} type="button">Search</button>
      </form>
    );
  }
}

There are many solutions for these issues : the bind() method, the that/self pattern, the arrow function.

这些问题有很多解决方案: bind()方法,that / self模式,arrow函数。

For more on how to fix this related issue issues, take a look at What to do when “this” loses context.

有关如何解决this相关问题的更多信息,请查看当“ this”失去上下文时该怎么办

这没有封装 (this has no encapsulation)

this creates security problems. All members declared on this are public.

this会带来安全问题。 this声明的所有成员都是公开的。

class Timer {
 constructor(callback, interval){
    this.timerId = "secret";
  }
}

const timer = new Timer();
timer.timerId; //secret

没有这个,没有定制的原型 (No this, no custom prototypes)

What if, instead of trying to fix this losing context and security problems, we get rid of it all together?

如果,而不是试图解决this失败的环境和安全问题,我们摆脱这一切在一起吗?

Removing this has a set of implications.

删除this具有一系列含义。

No this basically means no class, no function constructor, no new, no Object.create().

不, this基本上意味着没有class ,没有函数构造函数,没有new ,也没有Object.create()

Removing this means no custom prototypes in general.

删除this意味着通常没有自定义原型。

更好的语言 (A Better Language)

JavaScript is both a functional programming language and a prototype-based language. If we get rid of this, we are left with JavaScript as a functional programming language. That is even better.

JavaScript既是一种功能编程语言,又是一种基于原型的语言。 如果摆脱了this ,我们将剩下JavaScript作为一种功能性编程语言。 那更好。

At the same time, without this, JavaScript offers a new, unique way, of doing Object Oriented Programming without classes and inheritance.

同时,如果没有this ,JavaScript将提供一种新颖且独特的方式,无需类和继承即可进行面向对象的编程。

没有这个的面向对象编程 (Object Oriented Programming without this)

The questions is how to build objects without this.

问题是如何在没有this情况的情况下构建对象。

There will be two kind of objects:

将有两种对象:

  • pure data objects

    纯数据对象
  • behavior objects

    行为对象
纯数据对象 (Pure Data Objects)

Pure data objects contain only data and have no behavior.

纯数据对象仅包含数据,没有任何行为。

Any computed field will be fill-in at creation.

任何计算字段将在创建时填写。

Pure data objects should be immutable. We need to Object.freeze() them at creation .

纯数据对象应该是不可变的。 我们需要在创建时使用Object.freeze()

行为对象 (Behavior Objects)

Behavior objects will be collections of closures sharing the same private state.

行为对象将是共享相同私有状态的闭包的集合。

Let’s create the Timer object in a this-less approach.

让我们this方法创建 Timer对象。

function Timer(callback, interval){
  let timerId;
  function executeAndStartTimer(){
    callback().then(function makeNewCall(){
      timerId = setTimeout(executeAndStartTimer, interval);
    });
  }
  function stop(){
    if(timerId){
      clearTimeout(timerId);
      timerId = 0;
    }
  }
  function start(){
    if(!timerId){
      executeAndStartTimer();
    }
  }
  return Object.freeze({
    start,
    stop
  });  
}

const timer = Timer(getTodos, 2000);
timer.start();

The timer object has two public methods: start and stop. Everything else is private. There are no this losing context problems as there is no this.

timer对象有两个公共方法: startstop 。 其他一切都是私人的。 没有this丢失上下文的问题,因为没有this

For more on why to favor a this-less approach when building behavior objects take a look at Class vs Factory function: exploring the way forward.

有关为什么在构建行为对象时偏向于this方法的更多信息,请看一下Class vs Factory函数:探索前进的方向

记忆 (Memory)

The prototype system is better at memory conservation. All methods are created only once in the prototype object and shared by all instances.

原型系统在内存保存方面更好。 所有方法仅在原型对象中创建一次,并由所有实例共享。

The memory cost of building behavior objects using closures is noticeable when creating thousands of the same object. In an application we have a few behavior objects. If we take for example a store behavior object, there will be only one instance of it in the application, so there’s no extra memory cost when using closures to built it.

在创建数千个相同对象时,使用闭包构建行为对象的内存成本非常明显。 在一个应用程序中,我们有一些行为对象。 如果我们以一个商店行为对象为例,则在应用程序中将只有一个实例,因此使用闭包构建它时不会有额外的内存开销。

In an application there may be hundreds or thousand of pure data objects. The pure data objects don’t use closures, so no memory cost.

在一个应用程序中,可能有数百或数千个纯数据对象。 纯数据对象不使用闭包,因此没有内存成本。

没有这个的组件 (Components without this)

this may be required by many components’ frameworks, like React or Vue for example.

this可以由许多组件的框架是需要的,等React或Vue的例如。

In React, we can create stateless functional components, without this, as pure functions.

在React中,我们可以将无状态功能组件(不带this创建为纯函数。

function ListItem({ todo }){
  return (
    <li>
      <div>{ todo.title}</div>
      <div>{ todo.userName }</div>
    </li>
  );
}

We can also create stateful components without this with React Hooks. Take a look at the next example:

我们也可以使用React Hooks来创建有状态的组件,而无需this做。 看下一个例子

import React, { useState } from "react";
function SearchForm({ onSearch }) {
  const [query, setQuery] = useState({ text: "" });
  function handleChange(event) {
    const newQuery = Object.freeze({ text: event.target.value });
    setQuery(newQuery);
  }
  function search() {
    const newQuery = Object.freeze({ text: query.text });
    if (onSearch) onSearch(newQuery);
  }
  return (
    <form>
      <input type="text" onChange={handleChange} />
      <button onClick={search} type="button">Search</button>
    </form>
  );
};

删除参数 (Removing arguments)

If we get rid of this, we should also get rid of arguments as they have the same dynamic binding behavior.

如果我们摆脱了this ,我们也应该摆脱arguments因为它们具有相同的动态绑定行为。

Getting rid of arguments is pretty simple. We just use the new rest parameter syntax. This time the rest parameter is an array object:

消除arguments非常简单。 我们只使用新的rest参数语法。 这次rest参数是一个数组对象:

function addNumber(total, value){
  return total + value;
}

function sum(...args){
  return args.reduce(addNumber, 0);
}

sum(1,2,3); //6

结论 (Conclusion)

The best way to avoid this related problems is to not use this at all.

避免this相关问题的最佳方法是完全不使用this

JavaScript without this can be a better functional programming language.

没有this功能JavaScript可能是一种更好的功能编程语言。

We can build encapsulated objects, without using this, as collections of closures.

我们可以构建封装的对象,而无需使用this作为闭包的集合。

With React Hooks we can create this-less stateful components.

借助React Hooks,我们可以创建this无状态组件。

That being said, this can’t be removed from JavaScript without breaking all existing applications. However, something can be done. We can write our own code without this and let it be used in libraries.

话虽这么说, this不能从JavaScript而不会破坏现有的所有应用程序中删除。 但是,可以做一些事情。 我们可以不用this就可以编写自己的代码,并在库中使用它。

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!

发现功能JavaScript被称为 BookAuthority最好的新功能编程书籍

For more on applying functional programming techniques in React take a look at Functional React.

有关在React中应用函数式编程技术的更多信息,请查看 Functional React

Learn functional React, in a project-based way, with Functional Architecture with React and Redux.

通过带有React和Redux的功能架构 ,以基于项目的方式学习功能性React

Follow on Twitter

在Twitter上关注

翻译自: https://www.freecodecamp.org/news/removing-javascripts-this-keyword-makes-it-a-better-language-here-s-why-db28060cc086/

javascript关键字

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值