我很少有SML的经验。现在我想学习LiveScript,但是我仍然停留在数据类型上。那么,是否可以使用SML / Haskell / OCaml中的数据构造函数来创建类型呢?如果不是,创建数据类型的首选方法是什么?
发布于 2014-05-14 10:20:09
Haskell/SML和JavaScript/LiveScript/CoffeeScript的主要区别是:
在这些函数语言中,data类型定义用于编译时类型检查-JS的动态类型系统在运行时进行类型检查,因此不需要知道对象的确切结构。因此,没有data类型定义的直接转换。
1.只使用物体
如果您只想在程序中定义一次使用的数据结构,只需实例化一个新对象并赋予它一些属性:
// Create a new object with properties foo and bar
var MyThing = {
foo: 'a',
bar: 'b'
};
// Set the baz property of our new object
MyThing.baz = 'c';
// Remove the foo property from our object
delete MyThing.foo;这在LiveScript中几乎是相同的,除非语法不那么重:
MyThing = { foo: \a, bar: \b }
MyThing.baz = \c
delete MyThing.foo2.使用JS原型/ LiveScript类
如果您正在处理一个对象的许多实例,或者任何比定义一个一次性使用的对象更简单的东西,那么您可能希望使用对象原型。在JavaScript中,所有对象都有一个基于它们的原型对象。当在构造函数上调用new运算符时,将得到该函数的原型的副本,该副本用作构造函数的this上下文。例如:
// Define our constructor
var Thing = function(foo, bar) {
this.foo = foo;
this.bar = bar;
};
// Set a 'default' baz property for all Things
Thing.prototype.baz = 'c';
// Create a Thing
var myThing = new Thing('a', 'b');
// Inspect our properties
console.log(myThing.foo, myThing.bar, myThing.baz) // => 'a', 'b', 'c'这可以直接用LiveScript表示:
# Define a constructor
Thing = (foo, bar) ->
@foo = foo
@bar = bar
# Set a 'default' baz property for all Things
Thing::baz = \c
# Create a new Thing
my-thing = new Thing \a \b
# Inspect our properties
console.log myThing.foo, myThing.bar, myThing.baz或者,更简单地说,使用class语法表示(几乎完全一样)相同的内容:
class Thing
(@foo, @bar) ->
baz: \c
my-thing = new Thing \a \b3.不可变的数据结构
如果您来自Haskell或SML,您将熟悉不可变的概念,并编写无法执行副作用的函数。
在最初的示例中,我们声明了我们的对象myThing,然后对其进行了变异。在JS中,通过引用将对象传递到函数中,如果不使用调试器,副作用可能会使您很难判断出什么地方出了问题。
为了避免这种情况,我们可以使用Immutable.js库,它提供不可变的数据结构,例如映射(本质上是对象)和列表(本质上是数组)。
下面是使用Immutable.js映射重写的原始示例。
// Create a new Map (like a standard JS object, but immutable)
var myThing = Immutable.Map({ foo: 'a', bar: 'b' });
/*
* Set the baz property of our new Map
* Note that the original `myThing` object remains unchanged,
* because `myThing.set` returns a new Map with the changes supplied to set
*/
var myThingWithBaz = myThing.set('baz', 'c');
var myThingWithBazButNotFoo = myThingWithBaz.delete('foo');https://stackoverflow.com/questions/21266523
复制相似问题