On JavaScript Object-oriented programming _js object-oriented

Source: Internet
Author: User
Tags bind closure extend inheritance mixed
Sigh is to ease the seriousness of the atmosphere and lead to today's topic, "JavaScript object-oriented programming," Next, we are around the object-oriented several major keywords: encapsulation, inheritance, polymorphism, expand.
Encapsulation: The pattern of creating objects in JavaScript, which is considered by the individual to be a true encapsulation in the case of a closure, so let's start with a brief introduction to the closure and look at the following example:
Copy Code code as follows:

<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>

Do you look familiar? Yes, this is actually a simple closure application. To explain briefly: the variable defined in the function MyInfo above is accessible in its inline function showinfo (this is well understood), but when we assign the return reference of this inline function to a variable oldfish, This time the function showinfo is called outside the MyInfo function, but it can also access variables defined in the body of the function. Oh yeah!
To sum up the principle of closures: functions are run in the scope that defines them rather than invoke them. In fact, returning an inline function is also the most common way to create closures!
If the explanation above is too abstract, then let's reshape the above function to see if it's a distinct hierarchy:
Copy Code code as follows:

<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"). Showinfo ();
</script>

In the example of the coding style is the most common in ext Yui, public and private trenchant, at a glance. With closures, we can easily hide things that we don't want to be accessed directly from the outside, you want to access the variables defined within the function can only be accessed through a specific method, directly from the external access is not accessible, write very tired, spared a lap finally turned back, encapsulation well, is not to want to be seen by others hidden things! Ha ha......
The example above, if converted to JQ style, should be written in the following example, which belongs to the Portal wide open mode, where the variables defined are externally accessible (the following example if you instantiate an object first, The name or age attribute of the object is then accessed outside of the function, which can be read, of course, we can set some "unspoken rules" in this mode, let team development members understand which variables are private, and usually we put an underscore "_" in front of the private variables and methods to identify the alert signal! So as to achieve "encapsulation"!
Copy Code code as follows:

<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 are" + this.name + "I am" +this.age+ "years old";
alert (info);
}
};
IoldFish.func.init.prototype = Ioldfish.func;
Ioldfish ("Old Fish"). Showinfo ();
var oldfish = new Ioldfish ("Old Fish", 27);
alert (oldfish.name);
</script>

Some people may ask, which model is good? What does this say? Both methods have advantages and disadvantages, combined with the use of Bai! In short, a principle, must not be directly accessed by external objects, the closure of the package. "Must certainly" four words very abstruse, unceasingly practice can realize the true meaning!
Inheritance: When we mention this, I would like to add another sentence: The closure package is a disadvantage, not conducive to the derivation of subclasses, so closures are risky, encapsulation needs to be cautious! Visually, in the following example, the way to create an object is to use a "portal big open" pattern.
In JavaScript, inheritance is generally divided into three ways: "Class inheritance", "Prototype Inheritance", "mixed-element class". The following is a brief introduction to the principles of three types of inheritance.
A. Class inheritance: This is a common way of inheriting in the current mainstream framework, see the following example:
Copy Code code as follows:

<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>

The GetName method is not defined in the subgroup fish, but the instance object ioldfish of the subclass fish still calls the method because the subclass fish inherits the GetName method defined in superclass name. To explain this, the prototype of the subclass fish refers to an instance of the superclass, which, while not affirming the GetName method, is based on the prototype chain principle to find out if there is a method in the upper-level object that the prototype points to, if the method is not found, will continue to search for the original prototype object. This is actually the principle of inheritance. In particular, Fish.prototype.constructor = Fish, because the prototype of the default subclass should point to itself, but before the prototype is pointed to an instance object of the superclass, it is set back here. Of course, the code can be organized through a function, play the role of camouflage extend, look at the following code:
Copy Code code as follows:

function Extend (subclass,superclass) {
var F = function () {};
F.prototype = Superclass.prototype;
Subclass.prototype = new F ();
SubClass.prototype.constructor = subclass;
}

B. prototype inheritance, which is superior to class inheritance in terms of memory performance.
Copy Code code as follows:

<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 kernel of prototype inheritance is the Clone function, which is also the principle of the prototype chain, and the difference is that it directly clones the superclass, In this case, the subclass inherits all the properties and methods of the superclass. Specifically, this kind of inheritance does not need to create constructors, just create an object word variable, define the corresponding properties and methods, and then only need to pass the dot in the subclass. Symbols to refer to properties and methods.
C. Mixed class: A number of commonly used methods of common use of a unified package in a function, and then through the following function assigned to the class to use these methods. You can also selectively transfer the required methods for different classes.
Copy Code code as follows:

<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 think this is more abstract, difficult to explain, so the following from the overload and cover two aspects to brief.
Overload: The Agument function initially takes two arguments in the example above, but in subsequent calls, Agument (Fish,name, "Saylove") can also bring in any number of arguments, JavaScript overloads, is implemented by the user's own operation arguments this property in the function.
Overwrite: This is very simple, that is, the method defined in subclasses overrides this method if it has the same name as a method inherited from a superclass (this is not a method in overriding the superclass, notice).
Finally focus on the this and the execution context, in the previous encapsulation example, this is the instantiation object itself that represents the class in which this is located, but it is not the same as, for example, the event handling code defined by the HTML attribute, see the following code:
Copy Code code as follows:

<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>

The previous example has a button in the pop-up box does not display the properties of the instance object, because the execution context of this has changed, and the context in which he now resides should be the HTML tag for input, but the label does not have the GetName attribute. So nature cannot output the property value of this property! It is easy to see from this example that the execution context is determined at execution time and can be changed at any time.
Of course you can get rid of the code I commented on above and change the execution context of this by call to obtain the GetName method. The Apply method can also implement the ability to change the execution context, but a more graceful implementation of BIND is found in the prototype framework. Look at the realization of this method, have to lament the greatness of the ancestors ...
Copy Code code as follows:

Function.prototype.bind = function (obj) {
var method = This,
temp = function () {
return method.apply (obj, arguments);
};
}

Believe that if you can see the words, you can rely on these knowledge points, to write a simple script framework, a lot of practice, I believe in the near future can ace into the class! If you do not see clear, also do not worry, object-oriented is a little abstract, more practice, should be OK, refueling ...
This article first written to this, the next article can discuss with you, JavaScript design mode, please look forward to.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.