1

I come from C, C++, Java background. I want to create a struct/ class with some attributes and methods like:

MyClass{
    string text;
    array characters;
    printText(){ 
       print text;
    }
    printLen(){
       print characters.length();
    }
}

So next time I can create an object like above by just calling its constructor. How do I implement this in JavaScript? I am new to the programming principles followed in javascript, I want to create a custom data type here for reusability.

Nitin Labhishetty
  • 1,290
  • 2
  • 21
  • 41
  • 3
    Have you searched for anything yet? This is one of the most common questions. It is really simple. Good luck! – Zack Argyle Aug 14 '14 at 16:24
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript or just look for related questions is SO – briosheje Aug 14 '14 at 16:26
  • Great reference about javascript patterns: http://addyosmani.com/resources/essentialjsdesignpatterns/book/ take a look at Constructor Pattern. Also, Module and Singleton. – Christian Benseler Aug 14 '14 at 16:27

1 Answers1

1
function MyClass () {
    this.text = "";
    this.characters = [];
}

MyClass.prototype.printText = function () {
    console.log(this.text);
};

MyClass.prototype.printLen = function () {
    console.log(this.characters.length);
};

var instance = new MyClass();
instance.text = "test";
instance.characters.push('a');
instance.characters.push('b');
instance.printText();
instance.printLen();
Callebe
  • 1,087
  • 7
  • 18