| M Sheik 的个人资料udooz!照片日志列表 | 帮助 |
|
5月28日 Discipline in Object Orientation – [JavaScript – The Platform for Web 2.0 Part III]As per our "Anything on…" slogan, there are numerous ways we can define properties and methods for a class. This flexibility is more helpful in the implementation of bulky script animation, drag n drop, etc. But for a normal UI validation and business entity manipulation we have to follow a discipline. This will enable us to maintain and enhance a JavaScript code in long-time manner. Firstly, let us see the different ways to define a class. Object DeclarationWay 1See the code snippet 1. function Point(x, y) { this.x = x; this.y = y; this.toString = function(){return "(" + this.x + "," + this.y + ")";} } var point = new Point(10, 5); alert(point.toString()); //shows (10,5) Code Snippet 1 Figure 1 explains the nature of this approach.
A class named "Point" is defined with two properties (x and y) and a method "toString()". All the definitions are bundled within "Point" constructor. But technically, there are two issues with this approach; both make this approach as not optimal:
Way 2As we know that "new" operator in JavaScript enables us to create instance of a class. The function followed by "new" means that it acts as a constructor for the class. The declaration and initialization are happened in the same place as like code snippet 1. Also, JavaScript does the more work. The lifecycle of an object creation is depicted in figure 2.
In figure 2, upto point 3, there is no different between way 1 and way 2. After instantiating Point with "new", JavaScript add an object "prototype" to the instance "point" as property. By default, "prototype" object has a property named "constructor". Whenever, prorotype is initiated, it assigns the corresponding object's constructor function to its "constructor" property. If we define the Point class properties and methods in its prototype object, then it can be sharable. That is, each instance has separate "property" values and share same function point. See code snippet 2. Point = function(x, y) { this.x = x; this.y = y; };
Point.prototype.toString = function() { return "(" + this.x + "," + this.y + ")"; } Code Snippet 2 We can refactor code snippet 2 to create more discipline in the next article. 评论 (1)
引用通告此日志的引用通告 URL 是: http://udooz.spaces.live.com/blog/cns!1EA86C1FB1C134B8!198.trak 引用此项的网络日志
|
|
|