Object Inheritance in Javascript

Source: Internet
Author: User

There are two basic methods for class inheritance

Basic Principle of object impersonating: constructor uses the this keyword to assign values to all attributes and methods (constructor is actually only a value assignment function). Therefore, you can directly run the value assignment function within the class in one way, pass the this keyword to the new class. For example:

Java code

1. var A = function (){
2. This. A = 1;
3. This. B = 2;
4. Alert (this );
5 .}
6.
7. var B = function (){
8. This. AA = A; // converts this in A. The same method is used.
9. This. AA ();
10. delete this. AA; // Delete the intermediate method. Otherwise, the method of the original class may be overwritten in future operations.
11.
12. // or
13. A. Call (this, arg1, arg2 );
14. // or
15. A. Apply (this, [ARGs]);
16 .}
17.
18. var Ob = new B ();

VaR A = function (){
This. A = 1;
This. B = 2;
Alert (this );
}

VaR B = function (){
This. AA = A; // converts this in A. The same method is also used.
This. AA ();
Delete this. AA; // Delete the intermediate method. Otherwise, the method of the original class may be overwritten in future operations.

// Or
A. Call (this, arg1, arg2 );
// Or
A. Apply (this, [ARGs]);
}

VaR Ob = new B ();

Prototype chain

Basic principle: on the prototype chain, see (http://www.javaeye.com/topic/53537) an instance of the super class to the prototype object of the subclass, you can pass the fixed attributes and methods of the super class to the subclass, pay attention to one point, this method cannot pass parameters during instantiation. Therefore, classes are inherited in hybrid mode.

Class Definition and inheritance in prototype. js

Before 1.6.0:

Java code

1./** obsolete syntax **/
2. var person = Class. Create (); // use the class. Create method to create an empty class
3. Person. Prototype = {// define the method to prototype. Note that the class attributes are initialized through the initalize method.
4. initialize: function (name ){
5. This. Name = Name;
6 .},
7. Say: function (Message ){
8. return this. Name + ':' + message;
9 .}
10 .};
11.
12. var guy = new person ('miro ');
13. Guy. Say ('Hi ');
14. //-> "Miro: Hi"
15. // Inheritance Method in prototype:
16. var pirate = Class. Create (); // create an empty class;
17. // inherit from person class:
18. Pirate. Prototype = object. Extend (new person (), {// instantiate the superclass first, and then copy the methods in the superclass to the subclass,
19. // redefine the Speak method // note that the prototype class definition mechanism is not directly defined
20. Say: The function (Message) {// class attribute is passed through the intilize method, and all methods are
21. return this. Name + ':' + message + ', yarr! '; // Is directly defined in prototype, so the prototype is directly used.
22.} // all methods that inherit the superclass will not cause problems.
23 .});
24.
25. var John = new pirate ('long john ');
26. John. Say ('ahoy mate ');
27. //-> "Long John: Ahoy Matey, yarr! "

/** Obsolete syntax **/
VaR person = Class. Create (); // use the class. Create method to create an empty class
Person. Prototype = {// define the method to prototype. Note that the class attributes are initialized through the initalize method.
Initialize: function (name ){
This. Name = Name;
},
Say: function (Message ){
Return this. Name + ':' + message;
}
};

VaR guy = new person ('miro ');
Guy. Say ('Hi ');
//-> "Miro: Hi"
// Inheritance Method in prototype:
VaR pirate = Class. Create (); // create an empty class;
// Inherit from person class:
Pirate. Prototype = object. Extend (new person (), {// instantiate the superclass first, and then copy the methods in the superclass to the subclass,
// Redefine the Speak method // note that the prototype class definition mechanism is not directly defined
Say: function (Message) {// the attribute of the class is passed through the intilize method, and all the methods are
Return this. Name + ':' + message + ', yarr! '; // Is directly defined in prototype, so the prototype is directly used.
} // All methods that inherit superclasses will not cause problems.
});

VaR John = new pirate ('long john ');
John. Say ('ahoy mate ');
//-> "Long John: Ahoy Matey, yarr! "

Let's take a look at the implementation code of the class. Create method.

Java code

1. var class = {
2. Create: function (){
3. Return function () {// actually defines all attributes in the intiliaze method (actually a class,
4. This. Initialize. Apply (this, arguments); // The class is inherited through object impersonating.
5 .}
6 .}
7 .}

VaR class = {
Create: function (){
Return function () {// actually defines all attributes in the intiliaze method (actually a class,
This. Initialize. Apply (this, arguments); // then inherit the class through object impersonating
}
}
}

From prototype examples, we can fully understand the differences between object impersonating and prototype chain inheritance. Generally, attributes must be inherited by object impersonating, and methods must be inherited by prototype chain.

Versions later than prototype-1.6.0:

Java code

1. After 1.6.0, more extensions are made to prototype classes. For example:
2.
3./** new, preferred syntax **/
4. // properties are directly passed to 'create' Method
5. var person = Class. Create ({
6. initialize: function (name) {// you do not need to define an empty class. The position of the and method is changed.
7. This. Name = Name;
8 .},
9. Say: function (Message ){
10. return this. Name + ':' + message;
11 .}
12 .});
13.
14. // when subclassing, specify the class you want to inherit from
15. var pirate = Class. Create (person, {// The first parameter is class, which is directly inherited when a superclass are defined.
16. // redefine the Speak Method
17. Say: function ($ super, message ){
18. Return $ super (Message) + ', yarr! ';
19 .}
20 .});
21.
22. var John = new pirate ('long john ');
23. John. Say ('ahoy mate ');
24. //-> "Long John: Ahoy Matey, yarr! "
25.
26.
27.
28. // when declaring a subclass, rewrite the initialize of the subclass.

After 1.6.0, more extensions are made to prototype classes. For example:

/** New, preferred syntax **/
// Properties are directly passed to 'create' Method
VaR person = Class. Create ({
Initialize: function (name) {// you do not need to define an empty class, and the position of the and method is changed.
This. Name = Name;
},
Say: function (Message ){
Return this. Name + ':' + message;
}
});

// When subclassing, specify the class you want to inherit from
VaR pirate = Class. Create (person, {// The first parameter is class, which is directly inherited as a superclass when defining a class.
// Redefine the Speak Method
Say: function ($ super, message ){
Return $ super (Message) + ', yarr! ';
}
});

VaR John = new pirate ('long john ');
John. Say ('ahoy mate ');
//-> "Long John: Ahoy Matey, yarr! "

// Override the initialize of the subclass when declaring the subclass

Before 1.60

Java code

1. var animal = Class. Create ();
2. Animal. Prototype = {
3. initialize: function (name, sound) {// superclass, one or two parameters at the top
4. This. Name = Name;
5. This. Sound = sound;
6 .},
7.
8. Speak: function (){
9. Alert (name + "says:" + sound + "! ");
10 .}
11 .};
12.
13. var snake = new animal ("ringneck", "hissssssssssss ");
14. Snake. Speak ();
15. //-> alerts "ringneck says: hissssssssss! "
16.
17. var dog = Class. Create ();
18.
19. Dog. Prototype = object. Extend (new animal (),{
20. initialize: function (name) {// subclass, defining a parameter
21. This. Name = Name;
22. This. Sound = "woof ";
23 .}
24 .});
25.
26. var Fido = new dog ("Fido ");
27. Fido. Speak ();
28. //-> alerts "Fido says: Woof! "

VaR animal = Class. Create ();
Animal. Prototype = {
Initialize: function (name, sound) {// superclass, one or two parameters at the top
This. Name = Name;
This. Sound = sound;
},

Speak: function (){
Alert (name + "says:" + sound + "! ");
}
};

VaR snake = new animal ("ringneck", "hissssssssss ");
Snake. Speak ();
//-> Alerts "ringneck says: hissssssssss! "

VaR dog = Class. Create ();

Dog. Prototype = object. Extend (new animal (),{
Initialize: function (name) {// subclass, which defines a parameter
This. Name = Name;
This. Sound = "woof ";
}
});

VaR Fido = new dog ("Fido ");
Fido. Speak ();
//-> Alerts "Fido says: Woof! "

After 1.60

Java code

1. var animal = Class. Create ({
2. initialize: function (name, sound ){
3. This. Name = Name;
4. This. Sound = sound;
5 .},
6.
7.
8. Speak: function (){
9. Alert (this. Name + "says:" + this. Sound + "! ");
10 .}
11 .});
12. // subclassing animal
13. var snake = Class. Create (animal ,{
14. initialize: function ($ super, name) {// call the initliaze of the superclass in the form of $ super,
15. $ super (name, 'hisssssssss ');
16 .}
17 .});
18. var ringneck = new snake ("ringneck ");
19. ringneck. Speak ();
20. //-> alerts "ringneck says: hissssssssss! "
21.
22. var rattlesnake = new snake ("rattler ");
23. Rattlesnake. Speak ();
24. //-> alerts "rattler says: hissssssssss! "
25.
26. // mixing-In enumerable
27. var animalpen = Class. Create (enumerable ,{
28. initialize: function (){
29. var ARGs = $ A (arguments );
30. If (! Args. All (function (ARG) {return Arg instanceof animal }))
31. Throw "only animals in here! "
32. This. Animals = ARGs;
33 .},
34.
35. // implement _ each to use enumerable Methods
36. _ each: function (iterator ){
37. return this. Animals. _ each (iterator );
38 .}
39 .});
40. var snkepen = new animalpen (ringneck, rattlesnake );
41. snakepen. Invoke ('speak ');
42. //-> alerts "ringneck says: hissssssssss! "
43. //-> alerts "rattler says: hissssssssss! "

VaR animal = Class. Create ({
Initialize: function (name, sound ){
This. Name = Name;
This. Sound = sound;
},

Speak: function (){
Alert (this. Name + "says:" + this. Sound + "! ");
}
});
// Subclassing animal
VaR snake = Class. Create (animal ,{
Initialize: function ($ super, name) {// call the initliaze of the superclass in the form of $ super,
$ Super (name, 'sssssssss ');
}
});
VaR ringneck = new snake ("ringneck ");
Ringneck. Speak ();
//-> Alerts "ringneck says: hissssssssss! "

VaR rattlesnake = new snake ("rattler ");
Rattlesnake. Speak ();
//-> Alerts "rattler says: hissssssssss! "

// Mixing-In enumerable
VaR animalpen = Class. Create (enumerable ,{
Initialize: function (){
VaR ARGs = $ A (arguments );
If (! Args. All (function (ARG) {return Arg instanceof animal }))
Throw "only animals in here! "
This. Animals = ARGs;
},

// Implement _ each to use enumerable Methods
_ Each: function (iterator ){
Return this. Animals. _ each (iterator );
}
});
VaR snkepen = new animalpen (ringneck, rattlesnake );
Snakepen. Invoke ('speak ');
//-> Alerts "ringneck says: hissssssssss! "
//-> Alerts "rattler says: hissssssssss! "

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.