#21 JS: Object - Constructors

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


Like/Share/Follow

Feel free to comment and share your ideas below to learn together!
If you guys find this article helpful, please kindly do the writer a favor — LIKE this article./images/emoticon/emoticon12.gif


<<:  [Day21]Palindromes

>>:  观注的系列

[Day01] Tableau 轻松学 - 前言

前言 不论是在 IT 抑或是其他产业中,终究会遇到需将手上大量的数据视觉化,并转为有用的商业智能 (...

[Day26] VSCode Plugin - Edge Tools<未完>

Show the browser's Elements and Network tool insi...

Day 18 - 指标不能乱指会出事

WHY POINTERS? index - in dynamic allocation Basic...

威胁建模作业的前奏

如果顾问对客户说:「尊敬的贵宾,您说的都对...(後略○○字),但我们需要聚焦在关键○○○...(後...

[Day7] Virtual Networks

今天来介绍虚拟网路的部分,既然我们都有各种的虚拟机器、虚拟服务,那想当然,这些服务就是透过虚拟网路进...