JavaScript Object-oriented
A
An object is actually a reference type.
The value of the object is an instance of the reference type.
The reference type in JavaScript is a data structure,
Organize your data and functionality together.
It is also often called a class, but there is no class concept in JavaScript.
Although JavaScript is an object-oriented language,
There are no basic structures such as classes and interfaces supported by traditional object-oriented languages.
object creation and common operations
Using the new operator
var user = new Object (); Create an object using the new operator
User.Name = ' Beauty '; Adding properties to an object
User.age = 18;
user.address = ' Chengdu ';
Object literal
var user = {
Name: ' Beauty ',
Age:18,
Address: ' Chengdu '
};
Simple Way (Traditional assignment method)
var user = {};
User.Name = ' Beauty '; Adding properties to an object
User.age = 18;
user.address = ' Chengdu ';
The invocation of the property
There are two ways to call object properties:
The calling method is as follows:
Alert (User.Name + "" +user.age); Back to ' beautiful Chengdu '
Another way:
Alert (user[' name '] + "" +user[' age '); Back to ' beautiful Chengdu '
Add method
var user = {name: ' Beauty ',//Add attribute to Object
age:22, Address: ' Chengdu ',
Showinfo:function () {//Add a method
Alert (this.name+ "+this.age+" "+this.address");
},
Showhello:showhello//Add a method outside an object to an object
};
function Showhello () {
Alert (this.name+ "+this.age+" "+this.address");
}
Alert ("hello!");
}
} user.showinfo (); Call Method User.showhello ();
Two
Creating objects
We know that to create an object we can use the following code:
var user = new Object ();
User.Name = ' mm ';
User.age = 20;
user.address = ' Leshan ';
Creating objects in this way is simple and intuitive, and is the most basic way to create objects in JavaScript.
But there is a problem, if we need to create multiple objects, then I have to write a lot of duplicate code.
For example we want to create another object user1, we have to re-write the above code again,
This is not appropriate in the actual development process, so if there are too many objects, the amount of code will be greatly increased.
In order to solve this problem, we can use a method called Factory mode, this method
is to solve the problem of instantiating objects producing a lot of duplicate code.
Factory mode
function Create (name, age) {
var obj = new Object ();
Obj.name = name;
Obj.age = age;
Obj.show = function () {
return this.name + "+ this.age;
};
return obj;
}
var obj1= create (' Bclz ', 30); First Instance
var obj2= create (' Bcxb ', 20); A second instance
Alert (Obj1.show ());
Alert (Obj2.show ());
As we can see from the code above, the factory pattern solves the problem of large duplication of code during instantiation,
But there is a problem, that is to identify the problem, we simply can not find out exactly which object they are an instance of. Like what
Alert (typeof obj1); Object
Alert (obj1 instanceof Object); True
The above code indicates that Obj1 is an object, but we cannot know which object was created.
Constructors (construction methods)
function User (name, age) {//constructor mode
THIS.name = name;
This.age = age;
This.show = function () {
return this.name + ' +this.age;
};
}
When you create an object, you can use the new operator:
var user1 = new User (' mm ', 20); First Instance
var user2 = new User (' SS ', 10); A second instance
Now we can detect whether User1 or user2 belong to User.
Alert (user1 instanceof User); True
It can be seen that the method of using constructors solves the problem of repeated instantiation, and solves the problem of object recognition.
To create a new instance of the User object, use the new operator to build the instance object in this way, which takes the following 4 steps:
1. Create a new object;
2. Set the scope of the constructor to the new object (hence this new object that this is pointing to).
3. Execute the code within the constructor (add attributes to the new object);
4. Returns the new object.
However, the following two questions need to be noted:
Constructors are also functions
The only difference between a constructor and a function is that it is called differently, but the constructor is also a function, and there is no
A special syntax for defining constructors. Any function, as long as it is called by the new operator, can be thought of as a constructor function;
Any function, if not called by the new operator, is no different from a normal function, such as the User defined earlier:
Called as a constructor function
var user1 = new User (' mm ', 20);
User1.show (); SS 10;
Call as normal function
User (' mm ', 20);
Window.show (); SS 10;
There is no difference in the results, just as you can see, as the normal function call, the function of the This object point,
is actually a pointer to the window global object. When called by the New keyword, this is the object that is being pointed to, so
In fact, you can write it like this:
var o = new Object ();
User.call (o, ' SS ', 10);
O.show ();
By using the function method call to redefine the scope of the object, there is not much to explain, and when it comes to the details of the function, the method is carefully described.
This just means that you can change the scope of the object, in fact, change the point of this
Problems with constructors
The schema of the constructor is good, but it is not without drawbacks. The most important problem with constructors is that each method is
Create a new one. In the previous example, there is a show method in both User1 and User2, if we execute the following statement:
alert (user1.show==user2.show); The result returned is False
The result is false, which means that the method is actually a reference address. If we also repeatedly create multiple objects,
Then the methods in each object will open up new space in memory, thus wasting more space. To solve this problem,
We need to use instance properties or method sharing. We can use a flexible way to achieve the effect we want,
Which means that the Show method is no longer created repeatedly
function User (name, age) {
THIS.name = name;
This.age = age;
This.show = Show;
}
Function Show () {
Alert (this.name + "+ this.age);
}
Move the Show method outside, equivalent to the Show method as a global function, and then to the inside of the User constructor to refer to the Show method
, so that the this.show inside the User points to the same global function show, so the User1 and User2 we instantiate are
The share is implemented and can be called again:
alert (user1.show==user2.show); The result returned is true
But this is just a test, and if you want to have more properties or methods to share, it's not about defining more global functions or
It is not scientific or feasible. Therefore, we need to introduce another JavaScript object-oriented important
Concept prototypes
Three
Prototype prototype mode
Derivation of prototype concept through the drawbacks of constructor function
To clarify the prototype, we still have to review the constructor
To explain again in a simple example, we have a cat's constructor, as follows:
function Cat (name,color) {
THIS.name = name;
This.color = color;
}
This constructor is simple enough to say no more, so now add a constant property to the function
"Type" (kind), then add a method eat (Eat mouse). So, Cat becomes the following:
function Cat (name,color) {
THIS.name = name;
This.color = color;
This.type = "Cat animal";
This.eat = function () {alert ("Eat Mouse");
}
To generate an instance:
var cat1 = new Cat ("Da Mao", "Yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat Animals
Cat1.eat (); Eat mice
There seems to be no problem on the surface, but there is a big drawback in actually doing so. That is, for each instance object,
The type attribute and the Eat () method are identical content, and each time an instance is generated, it must be a duplicate content,
Use more memory. This is neither environmentally friendly nor inefficient.
Alert (cat1.eat = = cat2.eat); False
Therefore, in order for the Type property and the Eat () method to be generated only once in memory, then all instances point to that memory address,
Leads to prototypes.
What is a prototype?
The prototype object is actually an instance object of the constructor, and there is no intrinsic difference from the normal instance object.
You can include shared properties or methods for all instances of a specific type. The attribute value of this prototype is an object
(a collection of attributes), the default is only a property called constructor, pointing to the function itself.
For example, we simply define a function with a supertype name, and what attributes are not inside the function.
function Supertype () {
}
From what we see, there is nothing in the function, but there is a default prototype property, which is an object,
It points to its own address, and the prototype object itself has an attribute constructor, and this
property, and point to the function itself, a bit around, you can do a test by the following code to see the effect
Alert (Supertype.prototype)//object
Alert (SuperType.prototype.constructor)//popup function itself functions supertype () {
}
Prototype and constructor are the basic concepts of prototypes, and now it may be a bit dizzy, okay,
I go straight to the previous code, look at the difference, or the previous Cat constructor, and modify it:
function Cat (name,color) {
THIS.name = name;
This.color = color;
}
Cat.prototype.type = "Cat animal";
Cat.prototype.eat = function () {alert ("Eat Mouse")};
To generate an instance:
var cat1 = new Cat ("Da Mao", "Yellow");
var cat2 = new Cat ("Er Mao", "Black");
alert (Cat1.type); Cat Animals
Cat1.eat (); Eat mice
At this point all instances of the type attribute and the Eat () method are actually the same memory address, pointing to the prototype object,
As a result, operational efficiencies are increased.
Alert (cat1.eat = = cat2.eat); True
Verification method of Prototype mode
To match the prototype property, Javascript defines some helper methods that help us to use it.
isPrototypeOf ()
This method is used to determine the relationship between a Proptotype object and an instance.
Alert (Cat.prototype.isPrototypeOf (CAT1)); True
Alert (Cat.prototype.isPrototypeOf (CAT2)); True
hasOwnProperty ()
Each instance object has a hasOwnProperty () method that is used to determine whether a property is a local property or not.
or inherit from the properties of the prototype object.
Alert (Cat1.hasownproperty ("name")); True
Alert (Cat1.hasownproperty ("type")); False
In operator
The in operator can be used to determine whether an instance contains a property, whether it is a local property or not.
Alert ("name" in CAT1); True
Alert ("type" in CAT1); True
The in operator can also be used to traverse all properties of an object.
For (Var prop in cat1) {
Alert ("cat1[" +prop+ "]=" +cat1[prop]);
}
Take a look at the description and description of the prototype in the Advanced JavaScript programming book
function person () {}//Create person constructor
Person.prototype.name = "Nicholas"; Create a shared property name
Person.prototype.age = 29; Create a shared property age
Person.prototype.job = "Software Engineer"; Create a shared property job
Person.prototype.sayName = function () {//create shared function Sayname
alert (this.name);
};
Person1 and Person2 are created, each with sayname functions, and the values that pop up are the same
var person1 = new Person ();
Person1.sayname (); "Nicholas"
var person2 = new Person ();
Person2.sayname (); "Nicholas"
Alert (Person1.sayname = = Person2.sayname); True
Through the above, it can be seen that Person1 and Person2, they have a pointer to person.prototype inside,
Can be tested by the Isprototype method of the prototype.
Alert (Person.prototype.isPrototypeOf (Person1)); True
Alert (Person.prototype.isPrototypeOf (Person2)); True
function User () {};
var person3 = new User ();
Alert (Person.prototype.isPrototypeOf (Person3)); False
Alert (User.prototype.isPrototypeOf (Person3)); True
As an analogy, let's consider the data type in JavaScript-string,
Numbers, arrays, objects (object), dates (date), and so on.
We have reason to believe that these types are implemented as constructors within JavaScript,
Like what:
Defines the constructor of an array as a predefined type of JavaScript
function Array () {
// ...
}
Initializing an instance of an array
var arr1 = new Array (1, 56, 34, 12);
However, we prefer the following syntax definitions:
var arr2 = [1, 56, 34, 12];
Many methods (such as Concat, join, push) at the same time for an array operation should also be in the prototype property
defined in the. In fact, all of JavaScript's intrinsic data types have read-only prototype properties
(This is understandable: because if these types of prototype properties are modified, what predefined
Method disappears), but we can add our own extension method to it.
Extend a method that gets the minimum value to the JavaScript intrinsic type Array
Array.prototype.min = function () {
var min = this[0];
for (var i = 1; i < this.length; i++) {
if (This[i] < min) {
min = this[i];
}
}
return min;
};
Call the Min method on an instance of any array
Console.log ([1, +, 12].min ()); 1
Note: Here is a trap, after adding an extension method to the array's prototype, when using the for-in loop array,
This extension method will also be looped out. The following code illustrates this (assuming that the Min method has been extended to the array's prototype):
var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
Total + = parseint (Arr[i], 10);
}
Console.log (total); NaN
The workaround is also simple:
var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
if (Arr.hasownproperty (i)) {
Total + = parseint (Arr[i], 10);
}
}
Console.log (total); 103
Constructor
Constructor
Always points to the constructor that creates the current object. For example, the following:
Equivalent to var foo = new Array (1, 56, 34, 12);
var arr = [1, 56, 34, 12];
Console.log (Arr.constructor = = = Array); True
Equivalent to var foo = new Function ();
var Foo = function () {};
Console.log (Foo.constructor = = = Function); True
Instantiating an Obj object from a constructor
var obj = new Foo ();
Console.log (Obj.constructor = = = Foo); True
The above two pieces of code together to get the following conclusions
Console.log (Obj.constructor.constructor = = = Function); True
But when constructor met prototype, something interesting happened.
We know that each function has a default property of prototype, and this prototype
Constructor points to this function by default. As shown in the following example:
function person (name) {
THIS.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
var p = new Person ("Zhangsan");
Console.log (P.constructor = = = person); True
Console.log (Person.prototype.constructor = = = person); True
Merge the last two lines of code to get the following results
Console.log (P.constructor.prototype.constructor = = = person); True
When we re-defined the function's prototype,
(Note: In contrast to the above example, this is not a modification but an overlay),
Constructor's behavior is a bit strange, as in the following example:
function person (name) {
THIS.name = name;
};
Person.prototype = {
Getname:function () {
return this.name;
}
};
var p = new Person ("Zhangsan");
Console.log (P.constructor = = = person); False
Console.log (Person.prototype.constructor = = = person); False
Console.log (P.constructor.prototype.constructor = = = person); False
Why is it? It turns out that when overwriting person.prototype, it is equivalent to doing the following code:
Person.prototype = new Object ({
Getname:function () {
return this.name;
}
});
and constructor always points to the constructor that created itself, so at this point
Person.prototype.constructor = = = Object,
That is:
function person (name) {
THIS.name = name;
};
Person.prototype = {
Getname:function () {
return this.name;
}
};
var p = new Person ("Zhangsan");
Console.log (P.constructor = = = Object); True
Console.log (Person.prototype.constructor = = = Object); True
Console.log (P.constructor.prototype.constructor = = = Object); True
How to fix this problem? Method is also very simple, re-overwrite Person.prototype.constructor
Can:
function person (name) {
THIS.name = name;
};
Person.prototype = new Object ({
Getname:function () {
return this.name;
}
});
Person.prototype.constructor = person;
var p = new Person ("Zhangsan");
Console.log (P.constructor = = = person); True
Console.log (Person.prototype.constructor = = = person); True
Console.log (P.constructor.prototype.constructor = = = person); True
_proto_ Implicit prototypes for objects
Above we created two objects, Person1 and Person2, both of which point to the prototype of the person constructor,
This is because each object has a hidden property--"_proto_", which references the function that created the object.
Prototype.
That
Person1._proto_ = = = Person.prototype
This _proto_ is a hidden property, JavaScript does not want developers to use this property value, some of the lower version of the browser
This property value is not even supported.
Look at the following code:
Console.log (Object.prototype);
var obj = new Object ();
Console.log (obj.__proto__);
You will find that the same content was printed:
obj is essentially created by the object function, so obj._proto_=== object.prototype.
We can use a graph to represent.
About implicit prototypes, mainly related to the main principle of prototype inheritance, here just throw this concept a little introduction
Four
In different scopes
Different functions and variable declarations have different meanings
function Person (name,age) {
In constructors, variables or functions that are declared directly with Var
This, commonly referred to as a private variable or function, means that you can only use it in constructors
cannot be used in instantiated objects
var address = "Chengdu";
Any variable or function that is declared with this is generally referred to as a privileged variable or function.
THIS.name = name;
This.age = age;
}
A variable or function in a prototype, commonly referred to as a public variable or function.
means that all instantiated objects use the same variable or function
Person.prototype = {
Constructor:person,
Sex: "Male",
Show:function () {}
}
Person.prototype.sex = "male";
Person.prototype.show = function () {
// };
var user = {
}
Five
Prototypes (prototype)
Each function has prototype, and prototype has constructor, and the final constructor points to the function,
They form a connected pattern.
First, constructor binding
Let's take a look at the meanings of the following two functions:
function ClassA (scolor) {
This.color=scolor;
This.saycolor=function () {
alert (This.color);
};
}
function ClassB (scolor,sname) {
This.newmethod=classa;
This.newmethod (Scolor);
Delete This.newmethod;
This.name=sname;
This.sayname=function () {
alert (this.name);
};
}
Look at the start, this way seems very complex, in fact, the truth is very simple, is in the function of inheritance, a new variable
Newmethod, then point the ClassA pointer to the variable and call the method in ClassB, so
In fact, the scope of the Newmethod reference means that this point is the object ClassB instantiated.
Note: The last line removes a reference to ClassA so that it cannot be called later. All the new properties and
The new method must be defined after removing the code for the new method, otherwise overriding the related properties and methods of the superclass
To prove the validity of the front, run the following example
var obja=new ClassA ("Red");
var objb=new ClassB ("Blue", "Nicholas");
Obja.saycolor ();
Objb.saycolor ();
Objb.sayname ();
Because of the popularity of this inheritance method, ECMAScript added two new methods to the Function object,
Call () and apply (), so the method above can be overridden using the call or Apply method,
Binds the parent object's constructor to the child object, adding a line to the child object constructor:
function ClassB (scolor,sname) {
This.newmethod=classa;
This.newmethod (Scolor);
Delete This.newmethod;
Classa.call (This,scolor);
This.name=sname;
This.sayname=function () {
alert (this.name);
};
}
As you can see here, the first three lines of code are changed directly to the call method, so for the top example, we change to the following look,
You can directly implement the inherited
function Cat (name,color) {
Animal.apply (this, arguments);
THIS.name = name;
This.color = color;
}
var cat1 = new Cat ("Da Mao", "Yellow");
alert (cat1.species); Animals
Second, prototype mode
The second method is more common, using the prototype property. If the prototype object of "cat" points to a
Animal example, then all "cat" instances, can inherit Animal.
Cat.prototype = new Animal ();
Cat.prototype.constructor = Cat; (This line of code is last written in the function,
Let the prototype.constructor of the function point to the function itself,
This will prevent the pointer from being garbled. )
var cat1 = new Cat ("Da Mao", "Yellow");
alert (cat1.species); Animals
In the first line of the code, we point the Cat's prototype object to an instance of Animal.
Cat.prototype = new Animal ();
It is equivalent to completely removing the original value of the prototype object and then assigning a new value. But what does the second line mean?
Cat.prototype.constructor = Cat;
It turns out that any prototype object has a constructor property that points to its constructor.
If there is no "Cat.prototype = new Animal ();" This line, Cat.prototype.constructor is a pointer to
After adding this line, Cat.prototype.constructor points to Animal.
Alert (Cat.prototype.constructor = = Animal); True
More importantly, each instance also has a constructor property, which calls the prototype object's constructor property by default.
Alert (Cat1.constructor = = Cat.prototype.constructor); True
Therefore, after running "Cat.prototype = new Animal ();", Cat1.constructor also points to Animal
Alert (Cat1.constructor = = Animal); True
This obviously leads to the disorder of the inheritance chain (CAT1 is obviously generated with the constructor Cat), so we have to correct it manually,
Change the constructor value of the Cat.prototype object to Cat. This is the meaning of the second line.
Summarize JS Object-oriented