I. common inheritance Methods
Common inheritance methods in our daily development include: 1. Default Mode:
Child.prototype = new Parent();
2. Borrow constructors:
function Child(a, b, c, d) {Parent.apply(this, arguments);}
3. Borrow and set the prototype:
function Child(a, b, c, d) {Parent.apply(this, arguments);}Child.prototype = new Parent();
4. Sharing prototype:
Child.prototype = Parent.prototype;
5. Use a temporary constructor:
var Proxy = function() {};Proxy.prototype = Parent.prototype;Child.prototype = new Proxy();
6. Copy extend attributes:
function extend(parent, child) {child = child || {};for(var key in parent) {if(parent.hasOwnProperty(key)) {child[key] = parent[key];}}return child;}
Of course, in some JavaScript libraries (jquery), there are also shallow replication and deep replication. 7. Prototype inheritance mode:
Object.create(Parent);
Ii. Object. Create implement inheritance
In the future, this article will learn the seventh Inheritance Method object. Create () to implement inheritance. For a detailed description of this method, please stamp it here. Here are several examples to learn how to use this method:
var Parent = {getName: function() {return this.name;}}var child = Object.create(Parent, {name: { value: "Benjamin"},url : { value: "http://www.zuojj.com"}});//Outputs: Object {name: "Benjamin", url: "http://www.zuojj.com", getName: function}console.log(child);//Outputs: Benjaminconsole.log(child.getName());
Let's look at an example and add another inheritance:
var Parent = {getName: function() {return this.name;},getSex: function() {return this.sex;}}var Child = Object.create(Parent, {name: { value: "Benjamin"},url : { value: "http://www.zuojj.com"}});var SubChild = Object.create(Child, {name: {value: "zuojj"},sex : {value: "male"}})//Outputs: http://wwww.zuojj.comconsole.log(SubChild.url);//Outputs: zuojjconsole.log(SubChild.getName());//Outputs: undefinedconsole.log(Child.sex);//Outputs: Benjaminconsole.log(Child.getName());
We can see from the above that the object. Create () method implements chain inheritance and prototype chain inheritance. If you print the generated objects on the console, you can see clearly.
//Outputs: trueconsole.log(Child.isPrototypeOf(SubChild));//Outputs: trueconsole.log(Parent.isPrototypeOf(Child));
The isprototypeof () method tests whether an object exists in the prototype chain of another object. The above is the description of the object. Create method in this article. We hope to criticize and correct the content.
Use object. Create () to implement inheritance