JS Custom Constructors

上一篇 / 下一篇  2015-08-21 16:06:38 / 个人分类:JavaScript

Custom Constructors

But this approach of adding in properties one at a time for every object is tedious! Instead of always using the boring Object constructor, we can make our own constructors.

This way we can set the properties for an object right when it is created. So instead of using the Object constructor which is empty and has no properties, we can make our own constructors which have properties.

To see how this works, look at our Personconstructor in lines 1–4. This constructor is used to make Person objects. Notice it uses the keyword this to define the name andage properties and set them equal to the parameters given.

Now we can use this constructor to make our good friends bob and susan in only one line each! Look at lines 7–8: once we have the constructor, it's way easier to make people because we can include their name and ageas arguments to their respective constructors.

Instructions

Practice using the constructor to make a newPerson called george, whose full name is"George Washington" and age is 275.


Codes Samples:

// create a constructor for the StaffMember class

function StaffMember(name,discountPercent) {

    this.name = name;

    this.discountPercent = discountPercent;

};


var sally = new StaffMember("Sally",5);

var bob = new StaffMember("Bob",10);


//Create a StaffMember for yourself called me

var me = new StaffMember("john",20);


TAG:

 

评分:0

我来说两句

Open Toolbar