1

How do

  • prototypes
  • objects
  • constructors
  • "this"
  • functions

work in JS in relation to each other (and what exactly are they; is a constructor a function, object, prototype, "this")?

Can someone please clarify this? I have an idea of what each of them are and how they work, but not a clear one.

I think it would be easier to understand questions that arise, like, for example: "Is a.constructor the same as a.prototype.constructor", if one knows what these things are.

1
  • 1
    Did you even try "javascript object constructor" in Google? Commented Jun 24, 2011 at 7:24

1 Answer 1

2

Object - A collection of name-value pairs, for example:

var someObject = {
    aName: "aValue",
    name2: "value2"
}

Constructor - a function that 'creates' an object, for example:

function someObject(someParam) {
    this.someParam = someParam;
    this.getSomeParam = function() {
         return this.someParam;
    }
}

Prototype - a special type of object, from which other objects inherit properties. Every object has a prototype. You can use them to add a method to all instances of an object, for example:

String.prototype.doSomething = function() {
    //Do something with a String
}

Now that you have defined a doSomething method on the String prototype, all String objects can use it:

var myString = "Hello";
myString.doSomething();

For more information about the JavaScript language and how it works, I suggest you take a look at the ECMAScript spec, or for something a bit lighter, read this.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, especially for the links. I think I understand now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.