Spensy22
Spensy22

Reputation: 21

How to access properties of an object if it was created using a constructor function

This is my first question on stackoverflow and I am complete beginner in javascript. I was reading about object oriented programming in javascript using this article ,http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know>. In the section named "OOP in javascript", it describes two ways of creating and object:

var myObj = {name:"Richard", profession:"Developer"};

I know you can access the propertise of this object by

myObj.name // "Richard"

The Second way the article describes of creating an object is

    function People (name, profession) {} 
    var richard = new People (“Richard”, “Developer”)

How do I access the name property of this object ??

Also I haven't read the rest of the article past this topic. I am stuck until this concept is cleared.

Upvotes: 2

Views: 44

Answers (2)

Prabhu Murthy
Prabhu Murthy

Reputation: 9256

the second way is called the constructor pattern. for which you have to modify your code like below

function People (name, profession) {
 this.name = name;
 this.profession = profession;
} 

in the above code "this" refers to the individual instances that you would create with the "new" operator.

now we create the object.

var richard = new People (“Richard”, “Developer”);

and then access the properties like

richard.name;
richard.profession;

explained well here with great information on other ways to create objects.

Upvotes: 1

cfj
cfj

Reputation: 121

In the constructor function you need to do something like this:

function People (name, profession) {
    this.name = name;
    this.profession = profession;
}

Then you can access the properties like you did with the first method.

richard.name // 'Richard'

Remember that the constructor is nothing but an ordinary function. Calling it with new just means that it gets an empty object as its receiver, i.e the this value inside the function.

Upvotes: 1

Related Questions