2

I am just learning javascript and was wondering if someone could point me to or explain a good description between a custom data type and a regular class like object?

I was working through a sample code snip below to help me. Is a custom data type and a regular class like type object the same thing? I was confused on this point.

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

    this.getFullName = function() {
        return this.firstName + " " + this.lastName;
    };

    this.greet = function(person) {
        alert("Hello " + person.getFullName());
    };

}

var person1 = new Person("Bill", "Smith");
var person2 = new Person("John", "Doe");

person2.greet(person1);

alert(person1.getFullName());

Thanks in advance to all. Is this the answer?

Community
  • 1
  • 1
Rob
  • 531
  • 1
  • 7
  • 11
  • 3
    what is custom data type ? in js you can create object via Object.create / constructor functions / literal object. what u did here is constuctor function – Royi Namir Mar 12 '14 at 12:26
  • What is a "regular class"? JavaScript objects do not have "types". – Bergi Mar 12 '14 at 12:41
  • 1
    It was my understanding from another language that I said class, referring to class object. The guy below got what I meant and explained everything to me. Thanks – Rob Mar 12 '14 at 13:27

1 Answers1

2

In javascript, there are no classes ( but OOP is possible )

1.Primary data types include Arrays and int, string, float, etc.

2.Custom data types are also array kind of thing, except you can define properties and functions inside them.

Examples

For 1

var example1=1;// Example for the first one.

For 2

var example2 = {
    name: 'Hi',
    introduce: function () {
        alert("Hi from "+this.name);
    }
};

For the first one, you can just use the value or manipulate it.

For the second one, you can define what you want and you can also call functions, defined in that variable.

So, with example2 You can do this:

example2.name='Joe';
example2.introduce();// Will alert "Hi from Joe";

Note that, while you define your custom object, you can call its properties and functions with reference to this as I have used in this.name.

Since you are a newbie to javascript, also note that you'll need to use only var to create variables unlike int, string in other languages.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • I know this is a super old post, but modern JavaScript supports classes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – JeffryHouser Nov 22 '21 at 02:35