构造函数vs工厂函数 [英] Constructor function vs Factory functions

查看:185
本文介绍了构造函数vs工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在Javascript中澄清构造函数和工厂函数之间的区别。



何时使用一个而不是另一个?

解决方案

基本区别在于构造函数与 new 关键字一起使用(导致JavaScript到自动创建一个新对象,在该对象的函数中设置 this ,并返回该对象):

  var objFromConstructor = new ConstructorFunction(); 

工厂函数被称为常规函数:

  var objFromFactory = factoryFunction(); 

但是要将它视为工厂,它需要返回某个对象的新实例:如果它只是返回一个布尔值或其他东西,你不会称它为工厂函数。这不会像 new 那样自动发生,但它确实允许在某些情况下更灵活。



真的简单示例上面引用的函数可能如下所示:

  function ConstructorFunction(){
this.someProp1 = 1\" ;
this.someProp2 =2;
}
ConstructorFunction.prototype.someMethod = function(){/ *无论* /};

函数factoryFunction(){
var obj = {
someProp1:1,
someProp2:2,
someMethod:function() {/ *无论* /}
};
//其他代码以某种方式操纵obj
return obj;
}

当然,你可以使工厂功能比这个简单的例子复杂得多。 / p>

有些人更喜欢将工厂功能用于所有事情,因为他们不想记得使用 new (编辑:这可能是一个问题,因为没有 new 该函数仍然会运行,但不会如预期的那样)。我不认为这是一个优势: new 是该语言的核心部分,所以对我来说故意避免它有点武断 - 可能还要避免其他关键词如 else



工厂函数的一个优点是当要返回的对象可能有几种不同的类型,具体取决于某些参数。


Can someone clarify the difference between a constructor function and a factory function in Javascript.

When to use one instead of the other?

解决方案

The basic difference is that a constructor function is used with the new keyword (which causes JavaScript to automatically create a new object, set this within the function to that object, and return the object):

var objFromConstructor = new ConstructorFunction();

A factory function is called like a "regular" function:

var objFromFactory = factoryFunction();

But for it to be considered a "factory" it would need to return a new instance of some object: you wouldn't call it a "factory" function if it just returned a boolean or something. This does not happen automatically like with new, but it does allow more flexibility for some cases.

In a really simple example the functions referenced above might look something like this:

function ConstructorFunction() {
   this.someProp1 = "1";
   this.someProp2 = "2";
}
ConstructorFunction.prototype.someMethod = function() { /* whatever */ };

function factoryFunction() {
   var obj = {
      someProp1 : "1",
      someProp2 : "2",
      someMethod: function() { /* whatever */ }
   };
   // other code to manipulate obj in some way here
   return obj;
}

Of course you can make factory functions much more complicated than that simple example.

Some people prefer to use factory functions for everything just because they don't like having to remember to use new (EDIT: and this can be a problem because without new the function will still run but not as expected). I don't see that as an advantage: new is a core part of the language so to me deliberately avoiding it is a bit arbitrary - might as well avoid other keywords like else.

One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.

这篇关于构造函数vs工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆