3

Possible Duplicate:
What is the 'new' keyword in JavaScript?

I'm learning about prototypes in Javascript and wondered what this code is doing. It's not like what I've run across in Java or C#:

  function MyObject(Parameter)
  {
    this.testString = Parameter;
  }

  var objectRef = new MyObject( "myValue" );

What's going on with that new MyObject("value") bit? I understand that in javascript functions are objects, but I'm still wrapping my head around what's going on when you new() a function?

Community
  • 1
  • 1
larryq
  • 13,813
  • 35
  • 107
  • 181
  • http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful FFS I'm not going to be alowed to alter this shiza – Dale Aug 01 '12 at 07:04
  • good question, short: No classes, only objects. \n no sense? Good, you are a java kid – Dale Aug 01 '12 at 07:06

1 Answers1

2

What its doing is the variable objectRef is creating a new object so everything in that function can be called on the variable affecting itself only. Let me give you a demonstration:

var cat = new MyObject("Im a cat");
var dog = new MyObject("Im a dog");

console.log(cat.testString);
// "Im a cat"

console.log(dog.testString);
// "Im a dog"

I hope that's of some help.

Menztrual
  • 37,509
  • 11
  • 55
  • 68