如何使用工厂函数编写JavaScript [英] How to write JavaScript with factory functions
问题描述
我正在阅读这篇文章关于尝试在JavaScript中模仿OOP的危险,并且有以下内容:
I'm reading this article about perils of trying to mimic OOP in JavaScript and there's the following:
在JavaScript中,工厂函数只是构造函数减去
new
要求,全球污染危险和尴尬限制(包括恼人的首字母大写)习俗).
In JavaScript, factory functions are simply constructor functions minus the
new
requirement, global pollution danger and awkward limitations (including that annoying initial capitalized letter convention).
JavaScript不需要构造函数,因为任何函数可以返回一个新对象.使用动态对象扩展,对象文字和 Object.create()
,我们拥有了一切需要,没有一团糟.而 this
的行为就像在任何其他功能.哇!
JavaScript doesn’t need constructor functions because any
function can return a new object. With dynamic object extension,
object literals and Object.create()
, we have everything we
need — with none of the mess. And this
behaves just like it does in
any other function. Hurray!
我正确地假设,鉴于这种方法,我们应该替换以下代码:
Am I right to assume that given this approach we should replace this code:
function Rabbit() {
this.speed = 3;
}
Rabbit.prototype = {
this.getSpeed = function() {
return this.speed;
}
}
var rabbit = new Rabbit();
与此:
function RabbitFactory() {
var rabbit = {
speed: 3
};
Object.setPrototypeOf(rabbit, {
getSpeed: function() {
return this.speed;
}
})
return rabbit;
}
var rabbit = RabbitFactory();
推荐答案
不,那是错误的.您不应该使用 Object.setPrototypeOf
,最好使用 Object.create
(尽管它对结果没有影响).而且,如果您每次都使用对象文字创建原型,那么它将失去所有共享优势,因此您应该完全删除该原型或将其移到函数外以使其静态.编写工厂函数的正确方法是
No, that is wrong. You should not use Object.setPrototypeOf
, better use Object.create
(though it makes no difference for the result). And if you create the prototype from an object literal every time, it loses all of its sharing advantages, so you should either drop that completely or move it outside the function to make it static. The correct™ way to write the factory function would be
const protoRabbit = {
getSpeed: function() {
return this.speed;
}
};
function createRabbit() {
var rabbit = Object.create(protoRabbit);
rabbit.speed = 3;
return rabbit;
}
var rabbit = createRabbit();
这篇关于如何使用工厂函数编写JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!