Reflection Activity

An important point made in Mesch’s article is that the Internet has become a culture where people are opening up and expressing themselves freely online. The online community share their values and…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Hijack JavaScript Features in Your Own Objects

A clever way to reuse code you didn’t write

photo by the author

Writing code can be challenging. I think that’s one reason many people are attracted to the profession. It’s fun to put on your thinking cap each day and solve real-world problems with software. It’s really enjoyable.

That being said, just because it’s fun doesn’t mean that we should recreate things that have been created before. There are a lot of smart programmers out there who have developed a lot of code that we should leverage whenever we can.

That’s what we’re going to look at in this post. We’re going to stand on the shoulders of the giants who have come before us and hijack their code for use in our app.

Let’s speculate that we’re building an application where I can track my family members. I want to be able to add family members, remove family members and find them using their name.

It sounds like I need some kind of list. Considering that we’re working in JavaScript, Array is the first thing that comes to mind.

Let’s look at some code.

Here I have a class that’s going to represent my family. What you’ll notice is that I’m not creating an array anywhere. I’m going to have my family class act like an array.

You can see on line 7 inside the constructor, I add a length property. Arrays have a length property so we should too.

On line 10, we have the addFamilyMember() function. It takes the name of the family member and adds it to the Array.

Wait! What array? We didn’t create one.

Add a comment

Related posts:

Why Turning Off Notifications Improved My Focus and Energy

I have a confession. About three years ago, I turned off all notifications on my cell phone. Yep, no email, no Facebook, no Twitter, no Pinterest. Oh my. Why did I take such a drastic step? Because I…

Spring Mood

The pasture on a rainy spring day, poetry by A. Christine Myers

Unitization

Humans are interested in knowing about Nature. This is because humans are a part of Nature. Humans must react (inter-react) with Nature in order to survive. Mathematics is a way to interact with…