新手JavaScript OOP与功能 [英] Beginner JavaScript OOP vs Functional

查看:79
本文介绍了新手JavaScript OOP与功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始研究不同的编程风格(OOP,功能性,程序性)。



我正在学习JavaScript并开始使用underscore.js, 这个小部分的文档。
文档说underscore.js可以用于面向对象或函数式风格,并且这两种风格的结果是相同的。

  _。map([1,2,3],function(n){return n * 2;}); 
_([1,2,3])。map(function(n){return n * 2;});

我不明白哪一个功能正常,哪一个是OOP,我不明白为什么,甚至在对这些编程范例进行了一些研究之后。 解决方案 并不是功能性,但通常功能性语言强调数据和功能的简单性。

大多数函数式编程语言没有类的概念和属于对象的方法。函数对定义良好的数据结构进行操作,而不是属于数据结构。



第一个样式 _。map _ 命名空间中的一个函数。它是一个独立的函数,你可以返回它或者将它传递给另一个函数作为参数。

pre $函数compose(f,g) {
返回函数(data){
return f(g(data));
}
}

const flatMap = compose(_。flatten,_.map);

对于第二种样式不可能做同样的事情,因为方法实例本质上与用于构造对象的数据。所以我会说第一种形式是更多功能。



在任何一种情况下,通用函数式编程风格都是数据应该是函数的最后一个参数,使得更容易咖喱或部分应用更早的论点。 Lodash / fp ramda 通过以下map来签名。

  _。map(func,data ); 

如果函数curried,您可以通过仅传递第一个参数来创建特定版本的函数。

  const double = x => x * 2; 
const mapDouble = _.map(double);

mapDouble([1,2,3]);
// => [2,4,6]


I'm just starting to research different programming styles (OOP, functional, procedural).

I'm learning JavaScript and starting into underscore.js and came along this small section in the docs. The docs say that underscore.js can be used in a Object-Oriented or Functional style and that both of these result in the same thing.

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

I don't understand which one is functional and which one is OOP, and I don't understand why, even after some research into these programming paradigms.

解决方案

There's no correct definition for what is and isn't "functional", but generally functional languages have an emphasis on simplicity where data and functions are concerned.

Most functional programming languages don't have concepts of classes and methods belonging to objects. Functions operate on well-defined data structures, rather than belonging to the data structures.

The first style _.map is a function in the _ namespace. It's a standalone function and you could return it or pass it to another function as an argument.

function compose(f, g) {
  return function(data) {
    return f(g(data));
  }
}

const flatMap = compose(_.flatten, _.map);

It's not possible to do the same for the second style, because the method instance is intrinsically tied to the data used to construct the object. So I'd say that the first form is more functional.

In either case, the general functional programming style is that data should be the final argument to the function, making it easier to curry or partially apply the earlier arguments. Lodash/fp and ramda address this by having the following signature for map.

_.map(func, data);

If the function is curried, you can create specific versions of the function by only passing the first argument.

const double = x => x * 2;
const mapDouble = _.map(double);

mapDouble([1, 2, 3]);
// => [2, 4, 6]

这篇关于新手JavaScript OOP与功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆