-2

How do you create an object of a class and call a method from it? I've done this in Java and other languages, but I'm looking to learn the syntax in javascript.

For example I'm looking for something like this:

file1.js

var person = new Person("Joe");
person.getName();

Person.js

function Person() {
    this.name = name;
}

function getName(String name) {
    return name;
}

Thanks for any help in advance!

0

2 Answers 2

0

Javascript uses a very different inheritance model from Java. Read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

It's a prototype based, as oppose to a classical. It also doesn't do the type checking, so you'll have to do it yourself.

function Person(name) {
    this.name = name;
}
Person.prototype.getname = function () {
    return this.name;
}
Person.prototype.setName = function (name) {
    if (typeof name === 'string') {
      this.name = name;
    } else {
      throw new Error('parameter must be of a string type');
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, thank you for the link and example!
0

Try this

function Person(name) {
   this.name = name;
}

Person.prototype.getName = function() {
   return this.name;
}

1 Comment

oh wow that was easy, thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.