[Learning]#21 JS: Object — Constructors

Vida Lin
1 min readOct 9, 2021

About Constructors

“The way to create an ‘object type’, is to use an object constructor function.
Objects of the same type are created by calling the constructor function with the new keyword.”

by W3C School

As the example we mentioned in the last article, there was only one trip.
Now, if we have multiple trips’ score to count, we’ll need a constructor to help us.

Example: This time, we will have 2 trips

function Trip(name,score){ //When it comes to creating a construtor function, usually people use capital letter.
this.name=name; //"this" represents an empty object auto created by the system.
this.score=score;
this.outdoor=function(){
this.score=this.score+10;
};
this.rainyDay=function(){
this.score=this.score-5;
};
this.snacksnBBQ=function(){
this.score=this.score+20;
};
this.napping=function(){
this.score++;
};
this.report=function(){
alert(this.name+":"+this.score)
};

}

var trip1=new Trip("Couple Trip",70); //befor constructor, adding a "new"
trip1.outdoor();
trip1.napping();
trip1.report();

→ The result is 81

var trip2=new Trip("Company Trip",60);
trip2.rainyDay();
trip2.snacksnBBQ();
trip2.report();

→ The result is 75

Music of Today: Surrender by Ball Park Music

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Vida Lin
Vida Lin

Written by Vida Lin

PM, Relationship, Travel, or anything quirky but interesting.|Subscribe & buy Vida a drink @LikerLand, the bottom of each article. 在文章底下LikerLand訂閱、請Vida喝一杯飲料 ❤

No responses yet

Write a response