JavaScript prototypes, prototype chains, object replication and other principles and example analysis (bottom)

Source: Internet
Author: User

prototypes
Prototypes are important concepts in JavaScript object-oriented features and are too familiar concepts. Because in the vast majority
In object-oriented languages, objects are class-based (for example, Java and C + +), and objects are the result of class instantiation. And in
In the JavaScript language, there is no concept of class
①, an object is instantiated by an object. For example, classes in a class-based language
Like a mold, the object is poured from this mold, and in the prototype language, the prototype is like a piece of artwork.
Originals, we have copied many copies of the original from a 100% precision machine.
None of the examples in the previous section involved prototypes, just generating classes from constructors and new statements, let's see
See how to build objects together using prototypes and constructors.
function person () {}
Person.prototype.name = ' byvoid ';
Person.prototype.showName = function () {
Console.log (this.name);
};
var person = new person ();
Person.showname ();
The code above uses a prototype instead of a constructor to initialize the object. Doing so is defined directly within the constructor
What is the difference between attributes?
**The properties that are defined in the constructor are inherited differently from the prototype, and the child object needs to explicitly call the parent object to inherit the
Properties defined within the build function.
Any attributes defined within the constructor, including functions, are created repeatedly, and the same constructor produces the
Two objects do not share an instance.**
A function defined within a constructor has the overhead of a run-time closure, because a local variable within the constructor defines
function is also visible.
The following code can verify the above problem:
function Foo () {
var innervar = ' Hello ';
THIS.PROP1 = ' byvoid ';
THIS.FUNC1 = function () {
Innervar = ";
};
}
FOO.PROTOTYPE.PROP2 = ' Carbo ';
FOO.PROTOTYPE.FUNC2 = function () {
Console.log (THIS.PROP2);
};
var foo1 = new Foo ();
var foo2 = new Foo ();
Console.log (foo1.func1 = = foo2.func1); Output false
Console.log (Foo1.func2 = = FOO2.FUNC2); Output true
However, it does not mean that it is not good to create properties within a constructor, but that each has a suitable range. Then we
When to use prototypes, when do you use the constructor definition to create attributes?
* * Unless you have to use a constructor closure, try to define member functions with prototypes, as this can reduce overhead.
Try to define a general member, especially an object or an array, within a constructor, because a member defined with a prototype is more than one
instances are shared. **
Next, let's look at the prototype chain mechanism in JavaScript.
prototype chain
There are two special objects in JavaScript: Object and function, which are constructors that are used to
into objects. Object.prototype is the ancestor of all objects, Function.prototype is the original of all functions
Type, including constructors. I divide the objects in JavaScript into three categories,
A class is a user-created object,
A class is a constructor object,
A class is a prototype object.
A user-created object, that is, an object explicitly constructed with the new statement in a general sense.
A constructor object refers to a normal constructor, which is a function that generates a normal object through new calls.
The prototype object refers specifically to the object that the constructor prototype property points to.
Each of these three types of objects has aProtoproperty, which points to the prototype of the object, which can be traced back to the Object.prototype from any object along which it begins to traverse.
The constructor object has the prototype property, which points to a prototype object that, when created by the constructor, is created by the object'sProtoThe prototype property will point to the constructor's property.
The prototype object has the constructor property, which points to its corresponding constructor. Let's use the following example to understand the prototype:

function Foo () {}
Object.prototype.name = ' My Object ';
Foo.prototype.name = ' Bar ';
var obj = new Object ();
var foo = new Foo ();
Console.log (Obj.name); Output My Object
Console.log (Foo.name); Output Bar
Console.log (foo. Proto. Name); Output Bar
Console.log (foo. Proto. Proto. Name); Output My Object
Console.log (foo. Proto. constructor.prototype.name); Output Bar

We define a constructor called Foo (), which generates the object foo. We also generate prototype objects for object and Foo, respectively.
The intricate relationships between them are analyzed.

Replication of Objects
JavaScript and Java do not have the same pointer as the C language, and all of the object type's variables are pointing to the
As a reference, the assignment of a value between two variables passes an object and does not replicate the object, but simply passes the reference.
Sometimes we need to copy an object completely, how do we do it? The Java language has a clone method that can actually
Now object is copied, but there is no such function in JavaScript. So we need to implement such a function manually, a
It is a simple practice to copy all the properties of an object:

Object.prototype.clone = function () {
var newObj = {};
for (var i in this) {
Newobj[i] = this[i];
}
return NEWOBJ;
}
var obj = {
Name: ' Byvoid ',
Likes: [' node ']
};
var newObj = Obj.clone ();
Obj.likes.push (' Python ');
Console.log (Obj.likes); Output [' node ', ' Python ']
Console.log (Newobj.likes); Output [' node ', ' Python ']

The above code is an implementation of a shallow copy of an object (shallow copy), that is, copying only the properties of the base type, and
The properties of the shared object type. The problem with a shallow copy is that two objects share the object type's properties , such as the likes in the previous example
Sex points to the same array of numbers.
Implementing a full copy, or deep copy, is not an easy task, because in addition to the basic data
Type, there are many different objects, and there are complex structures inside the object, so it needs to be implemented in a recursive way:

Object.prototype.clone = function () {
var newObj = {};
for (var i) {
if (typeof (This[i]) = = ' object ' | | typeof (This[i]) = = ' function ') {
Newobj[i] = this[ I].clone ();
} else {
Newobj[i] = this[i];
}
}
return NEWOBJ;
};
Array.prototype.clone = function () {
var newarray = [];
for (var i = 0; i < this.length; i++) {
if (typeof (This[i]) = = ' object ' | | typeof (This[i]) = = ' function ') { br> Newarray[i] = This[i].clone ();
} else {
Newarray[i] = this[i];
}
}
return newarray;

};
Function.prototype.clone = Function () {
var = this;
var newfunc = function () {
return that.apply (this, arguments);
};
for (var i in this) {
Newfunc[i] = this[i];
}
Return newfunc;
};
var obj = {
Name: ' byvoid ',
Likes: [' node '],
Display:function () {
Console.log (this.name);
},
};
var newObj = Obj.clone ();
NewObj.likes.push (' Python ');
Console.log (obj.likes);//Output [' node ']
Console.log (newobj.likes);//Output [' node ', ' Python ']
Console.log (new Obj.display = = Obj.display); Output false

The above implementation looks perfect, and it not only replicates the complex structure of the object recursively, but also implements the depth of the function.
Copy. This method works well in most cases, but there is a situation where it can do nothing, such as the following code:
var obj1 = {
Ref:null
};
var obj2 = {
Ref:obj1
};
Obj1.ref = Obj2;
The logic of this piece of code is very simple, that is, two mutually referenced objects. When we try to use a deep copy to copy
Obj1 and Obj2, the problem arises. Because a deep copy is a recursive approach to encountering objects
Copy, the result can only be recycled indefinitely. In this case, the simple recursion has not been solved, must design a
Set * * Graph theory algorithm, analyze the dependencies between objects, establish a topology diagram, and then copy each vertex sequentially,
and reconstruct the dependencies between them * *.

JavaScript prototypes, prototype chains, object replication and other principles and example analysis (bottom)

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.