Lodash - 使用_.create()的价值是什么

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

Lodash库中,使用_.create()处理类和实例与其他更传统的方法有什么价值?

Docs for create

javascript lodash
3个回答
2
投票

我认为create()不是要替换现有的JavaScript继承/原型机制。根据我的经验,将一种类型的集合映射到另一种类型时非常方便:

function Circle(x, y) {
    this.x = x;
    this.y = y;
}

function Square(x, y) {
    this.x = x;
    this.y = y;
}

Square.prototype.coords = function() {
    return [ this.x, this.y ];
}

var collection = [
    new Circle(1, 1),
    new Circle(2, 2),
    new Circle(3, 3),
    new Circle(4, 4)
];

_(collection)
    .map(_.ary(_.partial(_.create, Square.prototype), 1))
    .invoke('coords')
    .value();
// →
// [
//   [ 1, 1 ],
//   [ 2, 2 ],
//   [ 3, 3 ],
//   [ 4, 4 ]
// ]

1
投票

我认为这是一种便利。在执行JS中的经典继承模型的常见任务时,它更简洁一些。

本地:

var User = function() {};

User.prototype = Object.create(Person.prototype);

Object.assign(User.prototype, {
  constructor: User,

  ...other stuff
});

_.create

var User = function() {};

User.prototype = _.create(Person.prototype, {
  constructor: User,

  ...other stuff
});

写的只是少一点。


0
投票

我在阅读一些lodash代码后看到的最大区别是Object.create第二个参数采用object.defineProperty arg的格式,它是一个属性描述符,而_.create只复制所有自己或继承的可枚举属性(从对象依赖nativeKeysIn)。

它主要简化了经典对象的定义。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.