Wednesday, May 12, 2010

JavaScript: Implementing OOPS in JavaScript

Implementing Object-oriented methodology in JavaScript:

I have just found this wonderful article on the NET….Just sharing with you…very useful.

Packaging: javascript to create the object model, individuals think through the closure to be on the up are the true meaning of the package, so first of all, our first a brief closure, watch the following examples:


<script type="text/javascript">

function myInfo(){

var name ="Old fish ",age =27;

var myInfo = "my name is" + name + "i am" + age +"years old";

function showInfo(){

alert(myInfo);

}

return showInfo;

}

var oldFish = myInfo();

oldFish();

</script>


So are not very familiar? Yes, it is actually a simple application of the closure. Easy to explain: myInfo function above defined variables, embedded in its function showInfo is accessible (this a very good understanding), but when we put the embedded function return value to a variable reference oldFish, this time function showInfo at myInfo function in vitro are called, but can access to the same definition of variables in the function body. oh yeah!

Summarize the principle of closure: the function is running at the definition of their role in the domain instead of calling them the role of the domain. In fact, an embedded function back closure is the most commonly used to create a way!

If you feel that too abstract to explain the above, then join us in reshaping the above function, take a look at this a number of distinct levels:


<script type="text/javascript">

var ioldFish = function(name,age){

var name = name,age = age;

var myInfo = "my name is" + name + "i am" + age +"years old";

return{

showInfo:function(){

alert(myInfo);

}

}

}

ioldFish("Old fish ",27).showInfo();

</script>


Example on the ext yui coding style is the more commonPublic-private distinction at a glance . Through the closure, we can easily put some do not wish to be the external direct access to the hidden things, you want to visit the definition of function variables, only through a particular method can only be a visit to that directly from the external visit is to visit not, writeVery tired , Rao has finally come to a circle, and package them, do not put that do not wish to be like other people to see things hidden them! ... Ha ha ...

Example, if converted on JQ's style, he should have written the following example, this model belong to the package open door model, which are defined variable can be external access to the (the following example, if you first instantiate an object , and then access objects in the external function name or age of the property can be read to) this mode of course, we can set up some "unspoken rules" so that team members understand what variables are private, often our man-made At the private variables and methods before the underscore "_", logo warning signals! In order to achieve "package"!


<script type="text/javascript">

var ioldFish = function(name,age){

return ioldFish.func.init(name,age);

};

ioldFish.func = ioldFish.prototype ={

init:function(name,age){

this.name = name;

this.age = age;

return this;

},

showInfo:function(){

var info = "my name is" + this.name +"i am " +this.age+"years old";

alert(info);

}

};

ioldFish.func.init.prototype = ioldFish.func;

ioldFish(" Old fish ",27).showInfo();

//var oldFish = new ioldFish("Old fish ",27);

//alert(oldFish.name);

</script>


Some people might ask, what model is good? This how I say that? Two methods have advantages and disadvantages, combined with the use of chant! All in all a matter of principle, we must be an external object can not directly access anything on the package it with closure. "Must must" words are profound, and constantly practice in order to understand the true meaning!

Succession: the mention of the time, the way want to add one more point: closure of a disadvantage package is not conducive to sub-class of derivatives, so there is the risk of closure, packages need to be cautious! Visual clarity, the following examples of ways to create objects using "open door-type" model.

At javascript in succession are generally divided into three ways: "category-type succession," "prototype inheritance", "element-type doped." Following is a brief introduction about the principle of three types of inheritance.

A. Class-style inherit: This is now commonly used in the mainstream framework of inheritance, facie Example:


<script type="text/javascript">

var Name = function(name){

this.name = name;

};

Name.prototype.getName = function(){

alert(this.name);

};

var Fish = function(name,age){

Name.call(this,name);

this.age = age;

};

Fish.prototype = new Name();

Fish.prototype.constructor = Fish;

Fish.prototype.showInfo = function(){

alert(this.age);

}

var ioldFish = new Fish("Old fish ",27);

ioldFish.getName();

</script>


Fish in the above-mentioned sub-class no getName method definition, but examples of Fish subclass object ioldFish still call to this method, This is because sub-class inherits Fish Superclass Name as defined in the getName method. Explain here the prototype subclass Fish refers to the superclass of an instance in the subclass Medium Fish did not affirm the getName method, but in accordance with the principle of the prototype chain will point to the prototype object of go on a search whether there is the method If not find the method, will always search for the initial prototype of the object. In fact, this is the principle of succession. Here in particular to explain, Fish.prototype.constructor = Fish; this, because of the default sub-class of the prototype should be a point to itself, but before the prototype point to put the super-class instance object, so here it is set to come back. Of course you can put related code through a function to organize themselves to play the role of camouflage extend

B. Prototype inheritance, speaking from memory performance is better than category-style inheritance.


<script type="text/javascript">

function clone(object){

var F = function(){};

F.prototype = object;

return new F();

};

var Name = {

name:"who's name",

showInfo:function(){

alert(this.name);

}

};

var Fish = clone(Name);

//Fish.name = "Old fish ";

Fish.showInfo();

</script>


Obviously, the prototype of the succession of the core is the clone function, are the prototype chain of the same principle, different clones are directly super-category, then sub-category on the super-class inherits all the attributes and methods. In particular, look, this kind of inheritance and Do not need to create constructor, only the words necessary to create an object variable, the definition of the appropriate properties and methods, and then in the sub-class only through the necessary dots "." symbols to invoke properties and methods of it.

C. Yuan doped categories: put some more commonly used generic methods function in a unified package, and then through the following functions assigned to use these methods to the class. Can also be for different types of selective transmission needs.


<script type="text/javascript">

function agument(receveClass,giveClass){

if(arguments[2]){

var len = arguments.length;

for(i=2;i<len;i++){

receveClass.prototype[arguments[i]] = giveClass.prototype[arguments[i]];

}

}

else{

for(method in giveClass.prototype){

if(!receveClass.prototype[method]){

receveClass.prototype[method] = giveClass.prototype[method];

}

}

}

};

var Name = function(){};

Name.prototype ={

sayLike:function(){

alert("i like oldfish");

},

sayLove:function(){

alert("i love oldfish");

}

}

var Fish = function(){};

var ioldFish = new Fish();

agument(Fish,Name,"sayLove");

ioldFish.sayLove();

ioldFish.sayLike();

</script>


Polymorphism: personally feel that the somewhat abstract, it is difficult to explain in words, so following on from the heavy load and coverage both in terms of easy to elaborate.

Overloading: agument this example above, the initial function with two parameters, but behind the call, agument (Fish, Name, "sayLove") into the same could be any number of parameters, javascript overloaded, are at function through the operation by the user's own arguments to the implementation of the property.

Coverage: This very simple, it is defined in sub-class methods with the class from the super-inherited methods of the same name, on the coverage of this method (in this case is not covered by the method of super class, pay attention to you), here is not a cumbersome !

Finally the focus of reference, let me talk about this and the implementation of the context, in front of the package to cite examples, this is that this type of instance where the object itself, but not uniform, an analogy, the definition of property through HTML Event handle code, see the following code:


<script type="text/javascript">

var Name = function(name) {

this.name = name;

this.getName = function () {

alert(this.name);

}

};

var ioldFish = new Name("Old fish "),

btn = document.getElementById('btn');

btn.onclick = ioldFish.getName;

//btn.onclick = function(){ioldFish.getName.call(ioldFish)};

</script>


Example on the mid-point of the button after the pop-up box does not show examples of object property, which is the implementation of this because the context has changed, he is now where the context should be the input of the HTML tags, but the tag does not exist getName This property, therefore can not output the property values of the property! From this example we can see that: the implementation of context are only identified in the implementation, it can be changed at any time.

Of course you can remove the top of my comment out of that code, call to change this through the implementation of the context, in order to gain the getName method. Ways same can apply to change the implementation of the context of implementation of the function, but in the prototype found in the framework of a more elegant way to achieve bind. Look at the implementation of this method you, great ancestors had to sigh ... ...


Function.prototype.bind = function(obj) {

var method = this,

temp = function() {

return method.apply(obj, arguments);

};

}


 

No comments:

Post a Comment