1

I'm a newbie programmer, but I already saw some things that can be done better or at least differently. For example, classes are made available to create new objects, like this:

var newObject = new className(params);

But is this really necessary, since functions can return an object? I mean, with the following code you could as well get rid of the new keyword:

var newFruit = function (confobj) {
  var instance = {};

  //Common to all fruits
  instance.edible = true;

  //Custom settings
  instance.color = confObj.color;
  instance.shape = confObj.shape;
  instance.sweetness = confObj.sweetness;
  instance.sweet = (instance.sweetness > 0);

  return instance;
};

var banana = newFruit({
  color: 'yellow',
  shape: 'long',
  sweetness: 8
});

So, what do would be the advantages of using JS classes that require the new keyword instead of using code like that provided in the example?

4

1 回答 1

3

There are no classes in javascript.

Constructors (i.e. functions designed to be called with the new operator) are handy where you want multiple instances of an object. There are efficiency and maintenance benefits to sharing methods using inheritance rather than adding duplicate methods to each object. An alternative is to use ES5 Object.create, which more or less does the same thing as new.

If only a single instance of an object is required, there is no need for a constructor. Closures can be used for "private" variables and methods.

Use whatever strategy suits your application, large projects often use a mix of the above. There is no one "best" solution.

于 2012-09-28T05:08:55.573 回答