Creating custom objects in JavaScript
来源:互联网 发布:云计算安全解决 编辑:程序博客网 时间:2024/05/07 16:17
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=parameterthis.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 functionfunction computearea(){var area=this.radius*this.radius*3.14return area}//second method functionfunction computediameter(){var diameter=this.radius*2return 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.14return 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=rthis.area=computeareathis.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 1256alert("area="+mycircle.area())//alerts 400alert("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
- Creating custom objects in JavaScript
- Creating Custom Exceptions in .NET
- creating and destroying objects in C++
- Creating and Deleting Custom Menus in Visio
- Creating Custom Classes in LotusScript, part 1
- Creating Custom Timer Jobs in Sharepoint
- Creating custom data graphics in Visio
- Creating custom and compound views in Android
- JavaScript Objects in Detail
- JavaScript Objects in Detail
- JavaScript Objects in Detail
- Custom Events in JavaScript
- Creating URL query parameters from NSDictionary objects in ObjectiveC
- How to sort an NSMutableArray with custom objects in it?
- Creating Custom Web Controls in C# Stats(转)
- Creating a custom Site Definition in MOSS 2007
- Creating custom and compound Views in Android - Tutorial(翻译)
- Part 82 - Creating custom validation attribute in asp.net mvc
- JavaScript html js图片切割系统,裁剪,图片处理
- C#反射命名空间浅析
- CEdit控件实现滚动显示
- TOMCAT输入IP地址不跟项目名就直接访问指定的web项目
- 程序员之死 完结篇
- Creating custom objects in JavaScript
- 自行启动的ASP.NET应用程序(VS2010和.NET 4.0)
- 星海第十四天
- 《ASCE1885的信息安全》の使用Crypto++的MD5算法对字符串进行哈希
- DesignWare 加密文件 综合成GTECH 以便FPGA使用
- C#改写方法学习笔记
- C#异步编程模式IAsyncResult浅析
- 马云:员工表现不好,老板要先检讨
- C#运算符重载学习总结