【发布时间】:2019-02-23 00:47:56
【问题描述】:
我正在使用构造函数模式来创建我的对象,如下所示;
// Traditional constructor function
const Car = function( color, speed, oil )
{
this.color = color;
this.config = { speed: speed, oil: oil };
// ...
}
Car.prototype.internal = function()
{
console.log( "internal" );
// ...
}
Car.prototype.gas = function()
{
this.internal();
console.log( this.color );
// ...
}
Car.prototype.brake = function()
{
console.log( this.config );
// ...
}
我想将我的设计更改为与此设计相同但具有工厂功能的设计。于是我写了如下代码;
// Factory Design with Delegation
const carProto = ( function()
{
const carPrototype = {};
// Private function
function internal()
{
console.log( "internal" );
// ...
}
// Public function
carPrototype.gas = function()
{
internal();
console.log( this.color );
// ...
}
carPrototype.brake = function()
{
console.log( this.config );
// ...
}
return carPrototype;
} )();
function carFactory( color, speed, oil )
{
return Object.assign( Object.create( carProto ),
{
color: color,
config: { speed: speed, oil: oil }
} );
}
最后,我按如下方式创建对象;
var mazdaF = carFactory( "red", 10, 130 );
var mazdaT = new Car( "yellow", 20, 120 );
我想知道这是否正确。如果这不是真的,任何人都可以帮助我以最佳方式实现它吗?
【问题讨论】:
-
好的,把代码粘贴到某个地方运行一下,好像可以用,没有什么特别的不足。
标签: javascript design-patterns constructor factory-pattern