在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)。
它主要简化了经典对象的定义。