Create a Javascript object from a User-Defined Function

In this article we will create a Javascript object from a User-Defined Function. Lets create the user-defined function first,

function person(name, salary, occupation) {
		this.name = name;
		this.occupation = occupation;
		this.salary = salary;
		this.working = working;
};

We use the this keyword in the above function to refer to the property of that function and also take note that the working property is actually a function itself which we will declare here.

function working(company) {
	return this.company = company; // assign the company name to the property with the same property's name 
                                       // within the person function then return that property.
}

Next create a new person object with the object.create method. Take note that we need to use the new keyword when creating a new person object from the User-Defined Function. The new operator is used to create an instance of an object.

var worker = Object.create(new person("Johnny", 2000, "Programmer"));

Finally print out each property of that object within the with keyword block.

with(worker) {
	console.log(name);
	console.log(occupation);
	console.log(salary);
	console.log(working("ABC")); // calling the working function to return the name of the working company
}

The outcome is as follow

Johnny
Programmer
2000
ABC

Hope you like this javascript function object tutorial let move on.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of