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.

3

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

6 Comments

this.characters.length rather than this.characters.lengt Moreover, we don't know whathe means by "print".
It is just an example.
I want to create a javascript library where I define such contructs. Is this a good way in such a context?
You must to declare your library in one file and include it using a HTML SCRIPT tag. <script type="text/javascript" src="path/to/your/library.js"></script>
I meant is it a good design principle?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.