0

I'm having a hard time understanding the difference between these two functions. Are they the same? It seems like in the first case, appleOne is the name of the object, and in the second case, appleTwo is the name of the function. However, I read that functions and objects are the same in Javascript, so I'm confused...

var appleOne = new function(color) {
    this.color = color;
}

function appleTwo (color) {
    this.color = color;
}

Reference: Code from http://www.phpied.com/3-ways-to-define-a-javascript-class/

codersun3
  • 165
  • 2
  • 4
  • 13

1 Answers1

1

The difference is that the object associated with the variable appleTwo is a function object, which the object associated with the variable appleOne is not a function: it is a "regular" object with the field color.

I wouldn't say that "functions and objects are the same" in JavaScript. What is true is that there are several kinds of objects in JavaScript:

  • regular objects
  • arrays
  • functions
  • regular expressions

In the first example, you used an anonymous function as a constructor, so the object you produced and assigned to appleOne is a "regular" object. The second example uses a function declaration to define a function.

If your question was not about the difference, but rather why the first case "works" (because it is not a very common pattern), there are several S.O. questions available with the answer.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Also, since no value is assigned to *color*, then `appleOne.color` is undefined. – RobG Jul 13 '15 at 00:20
  • Correct, that's a good thing to add to the answer. The answer itself holds because `Object.keys(appleOne) === ['color']`. But yes, the value is `undefined`. – Ray Toal Jul 13 '15 at 06:45