Question

I'm coming at this from the OOP world and trying to wrap my head around "classes" in Javascript. I'd like to be able to create a class with properties but not have to assign values to them right away. Something like the following:

var MyObject = function(id) {
    this.id = id;
    // Create the property so it is present on all instances but don't require it to be assigned to right away.
    this.friendId;
}

MyObject.prototype = {
    constructor: MyObject

    // Etc...
}

Is there a way to do this or am I just not getting how it works in Javascript?

Was it helpful?

Solution

Simply omit the property from the declaration:

function MyObject(id) 
{
    this.id = id;
}

var obj = new MyObject(123);
console.log(obj.friendId); // undefined

Alternatively, explicitly set it to null in the constructor.

OTHER TIPS

This Mozilla Developer Network article is a good read. It compares Class based and Prototype based languages and provides side by side codes samples in Java and in JavaScript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

Quoting from the article.

Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top