Javascipt syntax does not support "class" [ES6 has been supported], but there are methods for simulating classes. Today I mainly talk about the simulation "class" method in Javascipt and the summary and retrospect of the inheritance in JS.
The realization of "class" and inheritance in JS is not only the key but also the difficulty. Many students may be in JS "class" and inheritance have some understanding, but in-depth analysis of the time, feeling powerless, ambiguous.
Let's summarize some of the ways that JS defines "classes":
Method One: Structural function method
This method is a more classical method, we will often see. When you generate an instance, use the New keyword. Class, and can also be defined on top of the prototype object of the constructor.
function Person (name,age,job) {
this.name=name;
This.age=age;
this.job=job;
}
Person.prototype.sayname=function () {
alert (this.name);
}
var person1 = new Person ("John", "I", "Web FrontPage Manager");
var person2 = new Person ("Dick", "The", "Doctor");
Person1.sayname (); Eject "John"
Console.log (person2.name)//output "dick"
Method Two: Object.create () method
Method Object.creat () as an alternative to the new operator is ES5. In this way, "class" is an object, not a function.
var mymammal = {
name: ' Herb ' mammal ',
get_name:function () {return
this.name;
},
says:functi On () {return
this.saying | | '';
}
}
var mycat = object.create (mymammal);
Mycat.name = ' Henrietta ';
mycat.saying = ' Meow ';
Mycat.get_name = function () {
console.log (this.says + ' + this.name + this.says);
}
Mycat.get_name ();
Output:
function () {return
this.saying | | '';
} Henriettafunction () {return
this.saying | | '';
}
This method is currently deployed in the latest versions of the major browsers, including IE9. If you encounter an older browser, you can deploy it yourself with the following code.
if (! Object.create) {
object.create = function (o) {
function F () {}
f.prototype = O;
return new F ();
};
}
Method III: Minimalist approach
Packaging
This method does not use this and prototype, and the code is very simple to deploy. First, it also simulates "class" with an object. Within this class, define a constructor Creatfn (), which is used to generate the instance.
var dog= {
creatfn:function () {
//some code here
}
};
Then, in Creatfn (), define an instance object that takes the instance object as the return value.
var dog= {
creatfn:function () {
var dog= {};
Dog.name = "dog";
Dog.makesound = function () {alert ("Woof");};
return dog;
}
};
When used, the CREATFN () method is invoked, and the instance object can be obtained.
var dog1 = Dog.creatfn ();
Dog1.makesound (); Wang Woo
The advantage of this approach is that it is easy to understand, the structure is clear and elegant, consistent with the traditional "object-oriented programming" constructs, so the following features can be easily deployed.
Inherited
It is convenient to have one class inherit from another. As long as in the former CREATFN () method, the Creatfn () method of the latter is invoked. Define a animal class first.
var Animal = {
creatfn:function () {
var Animal = {};
animal.eat= function () {alert ("Dinner Meal");};
return animal;
}
};
Then, in the CREATFN () method of the dog, the Creatfn () method of the animal is invoked.
var dog= {
creatfn:function () {
var dog= animal.creatfn ();
Dog.name = "dog";
Dog.makesound = function () {alert ("Woof");};
return dog;
}
};
The resulting dog instance will inherit both the dog class and the animal class.
var dog1= dog.creatfn ();
Dog1.eat (); Dinner Meal
Private properties and Private methods
In the Creatfn () method, as long as the methods and properties that are not defined on the dog object are private.
var dog= {
creatfn:function () {
var dog= {};
var sound = "Wang barking";
Dog.makesound = function () {alert (sound);};
return dog;
}
};
The internal variable sound of the example above cannot be read externally and is read only by the dog public Method MakeSound ().
var dog1 = Dog.creatfn ();
alert (Dog1.sound); Undefined
Data sharing
Sometimes, we need all instance objects to be able to read and write the same internal data. This time, as long as the internal data, encapsulated within the class object, Creatfn () method outside.
var dog= {
sound: "Wang Woo",
creatfn:function () {
var dog= {};
Dog.makesound = function () {alert (dog.sound);};
Dog.changesound = function (x) {dog.sound = x;};
return dog;
}
};
Then, two instance objects are generated:
var dog1 = Dog.creatfn ();
var dog2 = Dog.creatfn ();
Dog1.makesound (); Wang Woo
At this point, if you have an instance object that modifies the shared data, another instance object can also be affected.
Dog2.changesound ("Whoo-hoo");
Dog1.makesound (); Whoo-hoo.
JS inheritance
On the inheritance, there are a lot of information on the Internet can be queried, but a lot of friends do not understand it deeply enough. When it comes to inheritance, if you don't check the data, you may not be able to tell the story. This shows that our basic knowledge is not solid enough. Not thoroughly understood. Today, I stand on the basis of predecessors, and then together with you to review the inheritance.
Two of the most common ways to inherit are:
- Prototype chain inheritance (inheritance between objects)
- Class inheritance (inheritance between constructors)
Prototype chain inheritance
What is a prototype chain inheritance? Here I will not say what definition. In fact, the parent is inherited with prototype.
As an example:
function Parent () {
this.name = ' Mike ';
}
function Child () {
this.age =.
}
Child.prototype = new parent ();//child inherits parent, through prototype, form chain
var test = new Child ();
alert (test.age);
alert (test.name);//Get inherited attribute
//continuation prototype chain inheritance
function Brother () {//brother construct
this.weight =
Brother.prototype = new Child ();//Continuation prototype chain inherits
var Brother = new Brother ();
alert (brother.name);/inherits parent and child, pops up Mike
alert (brother.age);/pops up 12
The example above, through the prototype, forming a chain, the child inherits the Parent,brother has inherited the child, finally brother both the child and the parent's attribute, but also has its own attribute. This is the inheritance of the prototype chain.
Class inheritance (borrow constructor)
Class inheritance is typically called a superclass constructor by using call or apply for the internal invocation of a subtype constructor. As an example:
function Parent (age) {
this.name = [' Mike ', ' Jack ', ' Smith '];
This.age = age;
}
function Child (age) {
parent.call (this,age);
}
var test = new Child (.
) alert (test.age);//21
alert (test.name);//mike,jack,smith
Test.name.push (' Bill ')
; alert (test.name);//mike,jack,smith,bill
The above two types of inheritance are the two most basic ways of inheriting.
In addition, there are some ways to inherit, we look at together!
Combined inheritance
Composite inheritance is usually the inheritance way in which the two inherited methods are grouped together.
Examples are as follows:
function Parent (age) {
this.name = [' Mike ', ' Jack ', ' Smith '];
This.age = age;
}
Parent.prototype.run = function () {return
THIS.name + ' are both ' + this.age;
};
function Child (age) {
parent.call (this,age);//object impersonate, give the super type to pass the parameter
}
child.prototype = new Parent ();//prototype chain inheritance
var test = new Child (21);//write New Parent (21) also line
alert (Test.run ());//mike,jack,smith are both21
Prototype inheritance
And above the prototype chain inheritance is only one word difference, but is not the same content. What we call archetypal inheritance, as we said in the last lesson, is to create a new class by Object.create (). Because this way old-fashioned browsers don't support it. Therefore, if we do not use object.create (), there can be alternative methods, as follows:
function obj (o) {
function F () {}
f.prototype = O;
return new F ();
}
This function enables us to object.create () the way we create classes!
The following examples are as follows:
function obj (o) {
function F () {}
f.prototype = O;
return new F ();
}
var box = {
name: ' Trigkit4 ',
arr: [' brother ', ' sister ', ' Baba ']
};
var B1 = obj (box);
alert (b1.name);//trigkit4
b1.name = ' Mike ';
alert (b1.name);//mike
alert (b1.arr);//brother,sister,baba
b1.arr.push (' parents ')
; alert (B1.arr);//brother,sister,baba,parents
var b2 = obj (box);
alert (b2.name);//trigkit4
alert (b2.arr);//brother,sister,baba,parents
Parasitic inheritance
Examples are as follows:
function Creatanother (original) {
var clone=new Object (original);
Clone.sayhi=function () {
alert ("Hi")
};
return clone;
}
var person={
Name: "Haorooms",
friends:["hao123", "Zhansan", "Lisi"
}
var antherperson= Creatanother (person);
Antherperson.sayhi ();//hi
Parasitic combination
function Inheritprototype (subtype,supertype) {
var prototype = object.creat (Supertype.prototype);
Prototype.constructor = subtype;
Subtype.prototype = prototype;
};
function Supertype (name) {
this.name = name;
this.colors = [' Red ', ' blue ', ' green '];
}
SuperType.prototype.sayName = function () {
console.log (this.name);
}
Function subtype (name, age) {
//Inheritance Property
Supertype.call (this,name);
This.age = age;
}
Inheritance method
Inheritprototype (subtype,supertype);
SubType.prototype.sayAge = function () {
console.log (this.age);
}
var instance = new Subtype ();
The inheritance of a class is basically a few ways. Let's say a little bit more about ES6 Class!
ES6 Implementation Class
Define class class point
{
constructor (x, y) {
this.x = x;
This.y = y;
}
ToString () {return
' (' +this.x+ ', ' +this.y+ ') ';
}
}
var point = new Point (2, 3);
Point.tostring ()//(2, 3)
point.hasownproperty (' x ')//True
point.hasownproperty (' y ')//True
Point.hasownproperty (' tostring ')//False
Point.__proto__.hasownproperty (' tostring ')//True
Inheritance of Class
Class ColorPoint extends Point {
constructor (x, y, color) {
super (x, y);//Call Constructor (x, Y) of the parent class
this.co Lor = color;
}
ToString () {return
This.color + ' + super.tostring ();//Invoke the parent class's toString ()
}
}