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

Lodash - What is the value of using _.create()

本文关键字:是什么 使用 create Lodash      更新时间:2023-09-26

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

用于创建的文档

我不认为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 ]
// ]

我认为这是一种方便。在执行在 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
});

只是少写了一点。

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

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

相关文章: