Object-oriented Javascript

Source: Internet
Author: User

Learn more about the object-oriented features of JavaScript from prototype. js

JS is a powerful language, flexible, and convenient. Currently, from a syntax perspective, only Ruby is better than it.

However, I am only familiar with the dynamic language: JS Ruby Python Flash's as is a few simple, it should be a good idea.

The JS syntax is simple and not complex in ruby. So sometimes I think she is cleaner (Ruby fans should not attack me, and I love Ruby very much )!

Prototype. JS is undoubtedly a beautiful job of JS. You should be able to learn something from it.

If you can only write simple verification code such as if and alert on the page using JS, or want to know more about JS, this article may be helpful to you.

Okay. Let's get started.

Now I suddenly think of thinking in Java, "Everything is right". In fact, I think this sentence is not suitable for Java, but more suitable for Js.

1. How to Construct (initialize) objects?

JS Code
  1. VaR prototype = {
  2. Version: '1. 5.0 _ RC1 ',
  3. Scriptfragment :'(? :) (\ N | \ r | .)*?) (? : <\/SCRIPT> )',
  4. Emptyfunction: function (){},
  5. K: function (x) {return x}
  6. }

In this way, an object (called prototype) and four members of the object: version, scriptfragment, emptyfunction, and K are initialized.

Let's also try:

JS Code
  1. VaR BBS = {
  2. Name: 'javaeye ',
  3. Version: '2. 0 ',
  4. Describe: "Be the best software development communication zone ",
  5. Sayhello: function () {alert ("Hello, I'm javaeye! ")}
  6. }

So you can use: BBS. Name or bbs. sayhello ()

See? Sayhello is a method. Don't be alarmed. "Everything is an object", so it is the same as name, except initialization or defined syntax. Do you think of the two poles in the Regular Expression in JS? Cute!

A method is an object, so it can be passed as a parameter or as a return value of a method.

Therefore, prototype has a version attribute, and a regular expression string matching the script, an empty method emptyfunction, and a method K, which only returns parameters.

No problem. Continue!

2. constructor?

Let's write a code segment first (when I was in middle school, I had very poor Chinese Language (when I had no Chinese language in College). I want to write code so that you can understand my real thoughts ):

JS Code
  1. VaR person = function (name) {// here, person is a method.
  2. This. Name = Name;
  3. }
  4. VaR bencode = new persion ("bencode"); // This is like Java!
  5. Alert (bencode. Name );

First look at the results:
From alert (bencode. Name); you can know that bencode is an object, and name is the property of bencode. It is correctly initialized to "bencode"

So var bencode = new persion ("bencode"); is to construct a new object. Person () is equivalent to the constructor.

Therefore, the new keyword is to construct a new object, call the corresponding method on the object, and return the object.

As mentioned above: if a method is used after new, it is equivalent to a constructor.

Then again, if var bencode = new persion ("bencode") constructs an object, like Java, is the person class?
But isn't person a method? But is the method not an object? Class is also an object?

All objects?

It's safe!

Okay. Check prototype. js.

JS Code
  1. VaR class = {
  2. Create: function (){
  3. Return function (){
  4. This. Initialize. Apply (this, arguments );
  5. }
  6. }
  7. }

Initialize a class object. It has a member and is a method. This method returns to another method (the method is an object, so it can be used as a parameter or return value)

So if we do this:

JS Code
  1. VaR A = Class. Create (); // At this time, a is a method, method body, which is explained below
  2. VaR A = new A (...); // use the new operator to construct a new object and call this method on this object (now)

According to the above analysis? A is regarded as a class. Haha class. Create (); // It is truly named
VaR A = new A (...); // It is also quite intuitive, that is, to construct a new object, the type is

The new operator constructs an object and calls a method. What does this method do? That is, there is no analysis above. Let's take a look at it first:

JS Code
  1. VaR class = {
  2. Create: function (){
  3. Return function () {// see [1]
  4. This. Initialize. Apply (this, arguments); // see [2]
  5. }
  6. }
  7. }

[1]. The new operator calls this method on the newly generated object.
[2]. Oh? The initialize method on this object is called and arguments is passed.
In other words, it is to delegate the constructed task to the initialize method.
Initialize? Where is it? See below, class extension (inheritance)

3. prototype?

Look at the old code section:

JS Code
  1. VaR person = function (name ){
  2. This. Name = Name;
  3. }
  4. VaR bencode = new person ("bencode ");

Bencode is not an autistic person. He should be able to introduce himself to javaeye.
Like this:

JS Code
  1. Bencode. sayhello ();

 
If the above functions cannot be implemented, all the above new items are junk.

So. Add "instance method" to the person class"

Question: How do I add static methods? The above class. Create is just a member of an object.

Okay, let's try again. (for integrity, copy the above words again)

JS Code
  1. VaR person = function (name ){
  2. This. Name = Name;
  3. }
  4. Person. Prototype = {// What is protype?
  5. Sayhello: function (){
  6. Alert ("Hi, javaeye, I'm" + this. Name );
  7. }
  8. }
  9. VaR bencode = new person ("bencode ");
  10. Bencode. sayhello ();

Run the code!

What is prototype? Please forget the prototype (prototype. JS) library for the moment. The name is the same!

Let's analyze the results again (for the first time, we used this method to analyze and obtain the role of new ),

We are thinking:
To run bencode. sayhello () properly
Bencode is an object that we already know
Sayhello () should be the method of the bencode object.
 
However, the bencode object is generated by the new operator, while the new operator acts on the "class" of person"
So, oh? There are two possibilities:
1. Is the new object generated by new person. prototype?
2. The members in person. prototype will be added to the new object by the new operator.

Let's look at it again:

JS Code
  1. Person. Prototype = {
  2. Sayhello: function (){
  3. Alert ("Hi, javaeye, I'm" + this. Name); // This is available here
  4. }
  5. }

This. name. What does this mean? So the first one may be disconnected.

Recall this section:

JS Code
  1. VaR person = function (name ){
  2. This. Name = Name;
  3. }

If this represents a new object.
The second case makes sense. New will put the member of the person. Prototype object into the new object. It is consistent with the current behavior.

Therefore, the members in the person prototype object will be added to the newly generated object (as I understand)
(I don't know if the JS interpreter is open-source. If I have time, I have to see how to implement it .)

Hey, the default prototype is object!

4. expansion? Inherit?

What is expansion? What is inheritance? ! What did I get from my dad?
Cannot figure it out!

Or the actual point:

There is a class A, which has a sayhello Method

JS Code
  1. VaR A = function (){
  2. }
  3. A. Prototype = {
  4. Sayhello: function (){
  5. Alert ("sayhello ")
  6. }
  7. }

I want to construct a Class B that inherits the object. This sentence is too abstract.

In fact, we may think like this:

JS Code
  1. VaR B = new B ();
  2. B. sayhello (); // call a's sayhello

This should be the first meaning of inheritance (reuse)

What should I do?

VaR B = function () {// here is a Class B
}

How to add "instance method "? Think of prototype !!!

B. Prototype = A. Prototype

Is that all right? Congratulations! The operation is successful!

Let's integrate it once

JS Code
  1. VaR A = function (){
  2. }
  3. A. Prototype = {
  4. Sayhello: function (){
  5. Alert ("sayhello ");
  6. }
  7. }
  8. VaR B = function (){
  9. }
  10. B. Prototype = A. Prototype;
  11. VaR B = new B ();
  12. B. sayhello ();

But what if B is like this?

JS Code
  1. VaR B = function (){
  2. }
  3. B. Prototype = {
  4. Sayhi: function (){
  5. Alert ("sayhi B ");
  6. }
  7. }

Should we add the content in A. prototype to the B. Prototype object instead of replacing it? Of course.

In this way, you can "Expand"

Digress? Where is polymorphism? Hey

Okay, enough. How is prototype. js "extended?

JS Code
  1. Object. Extend = function (destination, source ){
  2. For (VAR property in source ){
  3. Destination [property] = source [property];
  4. }
  5. Return destination;
  6. }

This is just to add the source member to the destination object. Where can we see the extension?

What if I do?

JS Code
  1. VaR A = function (){
  2. }
  3. A. Prototype = {
  4. Sayhello: function (){
  5. Alert ("sayhello ")
  6. }
  7. }
  8. VaR B = function (){
  9. }
  10. Object. Extend (B. prototype, A. Prototype); // Add the parent class (a) member first.
  11. Object. Extend (B. prototype, {// Add another class B member. If it is the same name, it overwrites and the behavior conforms to the "polymorphism"
  12. Sayhi: function (){
  13. Alert ("sayhi B ");
  14. }
  15. });

Recall the previous class. Create ():

JS Code
  1. VaR person = Class. Create ();
  2. VaR bencode = new person ("bencode ");

As mentioned earlier, when new is called, a new object will be created and the person method will be called. The person method will be delegated to the initialize method of "newly generated object ".

How to add the initialize method to the newly generated object? Haha, easy

JS Code
  1. Object. Extend (person. prototype ,{
  2. Initialize: function (){
  3. This. Name = Name;
  4. }//,
  5. // You can add other instance methods below.
  6. });

Therefore, the general format of creating a class using prototype is as follows:

JS Code
  1. VaR classname = Class. Create ();
  2. Object. Extend (classname. prototype ,{
  3. Initialize: function (...) {// This is equivalent to the constructor
  4. }
  5. //...
  6. });

If we want to inherit a class, as long:

JS Code
  1. VaR classname = Class. Create ();
  2. Object. Extend (classname. prototype, superclassname. Prototype );
  3. Object. Extend (classname. prototype ,{
  4. Initialize: function (...){
  5. }
  6. //...
  7. });

This basically applies to the object-oriented part.

I hope it will be helpful to you!

I wanted to write prototype. js source code again, but it was because of time, and the second was because it was not necessary to discover it.
This kind of things looks fast and slow to write. Haha!

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.