Abbafei
Abbafei

Reputation: 3136

prototypes, objects, constructors, "this", functions

How do

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.

Upvotes: 1

Views: 123

Answers (1)

James Allardice
James Allardice

Reputation: 166071

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.

Upvotes: 2

Related Questions