`
king_tt
  • 浏览: 2110562 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Creating custom objects in JavaScript

 
阅读更多

Tutorial introduction

All JavaScript coders eventually reach a stage where they would like to create and use their own objects, apart from the pre-built ones, such as document or Math. Custom objects allow you to build up your own personal JavaScript "toolbox" that extends beyond what the pre-build objects have to offer. After reading this tutorial, you'll learn how to create your very own JavaScript object, complete with custom properties and methods!

How to create your own basic object

Creating an object requires two steps:

  • First, declare the object by using an object function
  • Lastly, instantiate the newly created object by using the "new" keyword

Lets take this one step at a time. We will now proceed to create an object called "userobject", which, at this stage, does nothing:

Step 1: declare the object by using an object function

The first step towards creating an object requires us to define an object function. An object function is virtually identical in syntax as a regular function, although there are some differences which will surface later on. The object function is used to define and declare an object:

function userobject(parameter){
}

The parameter is optional, and with it, allows us to pass in values to an object. For example, in the pre-built object window.alert, the parameter is the text passed in to be alerted. Now, with just the above object function, we have in essence just created a new object called "userobject"! It does nothing at this stage, and will continue to do until we add in properties and methods. To use this object, all we have to do is instantiate it, by using the keyword "new".

Step 2: Instantiate the newly created object by using the "new" keyword

Once we've defined an object function, we have to instantiate it to actually use it. Instantiating an object function means using the keyword "new" in front of the object name, and then creating an instance of the object by assigning it to a variable:

<script type="text/javascript">
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject("hi")
</script>

"myobject" is now an object...an instance of "userobject", to be exact.

If you're a little confused at this stage, consider a more familiar example:

var image1=new Image(20,20)

The above should be review to us; we created an instance of the pre-built image object by assigning it to the variable image1. Well, this familiar process is exactly what we'll doing with the custom object above.

If you're the kind that need to actually see and touch an object before you believe its an object, the window.alert method can help:

<script type="text/javascript">
function userobject(parameter){
}
//myobject is now an object of type userobject!
var myobject=new userobject("hi")
alert(myobject)
</script>

Are you convinced now?

How to add properties to your own object

Thus far, our object "userobject" cannot do anything but take up space in a document. With some properties, that should all change. To add properties to a user defined object, directly embed the properties into the object function, with each property proceeded by the keyword "this" plus dot (.): In the below example, we'll extend "userobject" to contain two properties, each containing a string of text:

function userobject(parameter){
this.firstproperty=parameter
this.secondproperty="This is the second property"
}

Now, to use these properties, simply access them like accessing any other property:

<script>
var myobject=new userobject("hi there.")
//alerts "hi there."
alert(myobject.firstproperty)
//writes "This is the second property"
document.write(myobject.secondproperty)
</script>

How to add methods to your own object

Adding methods to a user defined object is a bit more complicated. We need to first declare and define a function for each method, then associate this function with the object function. For the sake of simplicity, we will simply call functions defined for methods "method functions." Lets get a clean start, and create a new object called "circle" that will contain methods that compute the area and diameter of a circle, respectively.

The first step to adding methods is to implement the method functions. Method functions define what a method does:

//first method function
function computearea(){
var area=this.radius*this.radius*3.14
return area
}

//second method function
function computediameter(){
var diameter=this.radius*2
return diameter
}

In the above case, we've created two method functions, "computearea" and "computediamter", which calculates various aspects of a circle. The two functions, as you can see, are just functions, with one major distinction. Take the first one, for example:

function computearea(){
var area=this.radius*this.radius*3.14
return area

What the heck is this.radius? It looks like a property of a custom object to me (back up and see how a property is defined in a custom object). Since a method function will eventually be connected to the custom object, it has access to the properties of the object. We haven't defined the properties yet, but we will, and the method functions will use them in its calculation.

We will now associate the two method functions above to the new object "circle", so they become methods of the object:

<script type="text/javascript">
/*the below creates a new object, and gives it the two methods defined earlier*/
function circle(r){
//property that stores the radius 
this.radius=r
this.area=computearea
this.diameter=computediameter
}
</script>

Finally, to use these methods, instantiate the object, and access the methods just like any other method:

<script type="text/javascript">
var mycircle=new circle(20)
//alerts 1256
alert("area="+mycircle.area())
//alerts 400
alert("diameter="+mycircle.diameter())
</script>

As you can see, creating your own objects requires quite a bit of work, but can be very rewarding and even necessary as your JavaScript becomes more sophisticated.

Source: http://www.javascriptkit.com/javatutors/object.shtml

分享到:
评论

相关推荐

    [Head.First.JavaScript.2008].Michael.Morrison.文字版.pdf

    作者:Michael.Morrison ...10 creating custom objects: Having It Your Way with Custom Objects 449 11 kill bugs dead: Good Scripts Gone Wrong 485 12 dynamic data: Touchy-Feely Web Applications 537

    Head First Javascript(en par2)

    10 creating custom objects: Having It Your Way with Custom Objects ————449 11 kill bugs dead: Good Scripts Gone Wrong ————485 12 dynamic data: Touchy-Feely Web Applications ————537

    Learning Three.js: The Javascript 3D Library for WebGL

    Three.js is a JavaScript 3D library that offers a wide range of features for creating and displaying stunning 3D computer graphics on a web browser in an intuitive manner using JavaScript without ...

    jcef bulid x64

    It provides close integration between the browser and the host application including support for custom plugins, protocols, JavaScript objects and JavaScript extensions. The host application can ...

    Apache Wicket Cookbook.pdf

    Creating a client-side JavaScript tabbed panel 140 Using borders to decorate components 143 Creating a collapsible border 148 Chapter 7: Deeper into Ajax 157 Introduction 157 Adding Ajax ...

    Pro AngularJS

    15. Creating Custom Directives 16. Creating Complex Directives 17. Advanced Custom Directive Features Part 3 – AngularJS Modules and Services 18. Working with Modules and Services 19. Services for ...

    python3.6.5参考手册 chm

    The json module: JavaScript Object Notation The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific ...

    Unity.in.Action.Multiplatform.Game.Development.in.Csharp

    file and a test web page 282 ■ Communicating with JavaScript in the browser 283 Adjusting Player Settings: 280 ■ Platform-dependent 282 ■ Building the Unity CONTENTS xiii 12.3 Building for mobile ...

    Joomla! 1.5 Development Cookbook.pdf

    Creating a filter header for tabular data in an MVC component 213 Filtering tabular data in an MVC component 217 Creating toggle-enabled order column headers for tabular data in an MVC component ...

    Django 1.0 Website Development.pdf

    The jQuery JavaScript framework 99 Element selectors 100 jQuery methods 100 Hiding and showing elements 101 Accessing CSS properties and HTML attributes 102 Manipulating HTML documents 103 ...

    WordPress 3 Plugin Development Essentials.pdf

    Displaying custom data in your Templates 158 Copying a theme 158 Modifying the theme 159 Granular display of custom fields 161 Bonus for the MySQL curious 163 Known limitations 164 Summary 165 ...

    GWT in Action

    approaches to creating your application, including by hand and by using an IDE wizard. xxvi ABOUT THIS BOOK Chapter 3 is the first step you’ll take away from the default GWT application and toward ...

    Beginning Microsoft Visual CSharp 2008 Wiley Publishing(english)

    Projection: Creating New Objects in Queries 909 Projection: Method Syntax 912 Select Distinct Query 912 Any and All 914 Ordering By Multiple Levels 916 Multi-Level Ordering Method ...

    Python Cookbook英文版

    2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership ...

    CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)

    Creating Windows Service Projects in VS2008 709 Coding Windows Services 712 Installing a Windows Service 717 Building a Controller to Communicate with a Windows Service 720 Summary 722 32 ...

    ros by example for indigo volume 2

    3.8.3 Testing SMACH navigation in the ArbotiX simulator............................................23 3.8.4 Accessing results from a SimpleActionState.....................................................

Global site tag (gtag.js) - Google Analytics