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

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

问题描述

谁能解释一下 Javascript 中构造函数和工厂函数之间的区别.

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

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

When to use one instead of the other?

推荐答案

基本的区别在于构造函数使用了 new 关键字(这会导致 JavaScript 自动创建一个新对象,setthis 函数内的那个对象,并返回对象):

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();

但要使其被视为工厂",它需要返回某个对象的新实例:如果它只是返回一个布尔值或其他东西,您就不会称其为工厂"函数.这不会像 new 那样自动发生,但它确实为某些情况提供了更大的灵活性.

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.

工厂函数的一个优点是当要返回的对象根据某些参数可以是几种不同的类型时.

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

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

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