What is the inheritance of non-constructors?
For example, there is now an object called "Chinese".
var Chinese = {
Nation: ' China '
};
There is also an object called "Doctor".
var Doctor ={
Career: ' Doctor '
}
How can I let "Doctor" to Inherit "Chinese", that is, how can I generate a "Chinese doctor" object?
It is important to note that both objects are ordinary objects, not constructors, and cannot be implemented using constructor methods for "inheritance."
Second, the object () method
The object () function can do this.
function Object (o) {
function F () {}
F.prototype = O;
return new F ();
}
This object () function, in fact, only do one thing, is the prototype property of the object, pointing to the parent object, so that the child object and the parent object together.
Three, shallow copy
There is another way of thinking: to copy all the attributes of a parent object to a child object, you can also implement inheritance.
The following function is making a copy:
function Extendcopy (p) {
var c = {};
for (var i in P) {
C[i] = P[i];
}
C.uber = p;
return C;
}
When used, write this:
var Doctor = extendcopy (Chinese);
Doctor.career = ' Doctor ';
alert (doctor.nation); China
However, there is a problem with such a copy. That is, if the parent object's property is equal to an array or another object, then actually the child object obtains only one memory address, not a real copy, so there is a possibility that the parent object will be tampered with .
Now add a "birthplace" property to Chinese, whose value is an array.
chinese.birthplaces = [' Beijing ', ' Shanghai ', ' Hong Kong '];
We then add a city to the birthplace of doctor:
Doctor.birthPlaces.push (' Xiamen ');
The code is as follows:
Output:
Four, deep copy
The so-called "deep copy" is the ability to make real-world copies of arrays and objects. Its implementation is not difficult, as long as the recursive call "shallow copy" on the line.
function Deepcopy (p, c) {
var c = C | | {};
for (var i in P) {
if (typeof p[i] = = = ' object ') {
C[i] = (P[i].constructor = = = = Array)? [] : {};
Deepcopy (P[i], c[i]);
} else {
C[i] = P[i];
}
}
return C;
}
Use this to write:
var Doctor = deepcopy (Chinese);
Now, add an attribute to the parent object, and the value is an array. Then, modify this property on the child object:
chinese.birthplaces = [' Beijing ', ' Shanghai ', ' Hong Kong '];
Doctor.birthPlaces.push (' Xiamen ');
At this point, the parent object will not be affected.
alert (doctor.birthplaces); BEIJING, Shanghai, Hong Kong, Xiamen
alert (chinese.birthplaces); BEIJING, Shanghai, Hong Kong
Currently, the jquery library is using this method of inheritance.
Full code:
Output:
JavaScript Object-oriented programming (IV): Inheritance of non-constructors