Rohan Sobha
Rohan Sobha

Reputation: 395

Why aren't the properties of my object logged to the console?

Below, I have constructed an object called person and I want to log its first and last name(combined with some strings) to the console, but it does not work. I would be glad if somebody could help me out. Thank you in advance.

function person(last, first, birth, marriage) {
this.lastName = last;
this.firstName = first;
this.birthDate = birth;
this.married = marriage;
}

var lovely = new person("Doughnut", "Glazed", "7-8-1990", true);

var callPerson = function(){
console.log("Hey " + person.firstName + " " + person.lastName);
}

callPerson(lovely);

Upvotes: 0

Views: 29

Answers (3)

shaik
shaik

Reputation: 35

Where is the argument lovely storing it should have an parameter to store and use

function person(last, first, birth, marriage) {
this.lastName = last;
this.firstName = first;
this.birthDate = birth;
this.married = marriage;
}

var lovely = new person("Doughnut", "Glazed", "7-8-1990", true);

var callPerson = function(obj){
console.log("Hey " + obj.firstName + " " + obj.lastName);
}

callPerson(lovely);

Upvotes: 0

h7r
h7r

Reputation: 5074

It is not being logged because, in callPerson, the variable person refers to the function (constructor) person, since this name is not overridden in the scope of the function. This means you are not referring to some specific instance, but the class. Passing one instance as parameter doesn't change this since the function does not expect it; in effect, the passed parameter is not used in any means.

Think of this as attempting to log a class property, not one instance's.

Changing callPerson in the following way should solve your issue. Note that now the fields accessed are from the parameter p.

var callPerson = function(p){
    console.log("Hey " + p.firstName + " " + p.lastName);
}

Upvotes: 0

Halcyon
Halcyon

Reputation: 57709

You have a scoping issue:

var callPerson = function(person /* argument needs to be here */){
    console.log("Hey " + person.firstName + " " + person.lastName);
}

So person is the function, not the object lovely.


Minor code style remark: classes are typically capitalized, exactly to avoid this kind of confustion. Use function Person () {/**/} instead.

Upvotes: 3

Related Questions