-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!

Jon Perron
  • 83
  • 9

2 Answers2

0

Try this

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

Person.prototype.getName = function() {
   return this.name;
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
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');
    }
}
sergeyz
  • 1,339
  • 10
  • 14