Use Object.create () implementation inheritance: https://www.cnblogs.com/cuew1987/p/4075027.html
Object.create implementation class with style inheritance: https://www.jianshu.com/p/561432a109d6
A common inheritance
Our daily development of common inheritance are: 1, the default mode:
1
|
Child.prototype =
new
Parent();
|
2, borrowing constructors:
1
2
3
|
function
Child(a, b, c, d) {
Parent.apply(
this
, arguments);
}
|
3, borrowing and setting Prototype:
1
2
3
4
|
function
Child(a, b, c, d) {
Parent.apply(
this
, arguments);
}
Child.prototype =
new
Parent();
|
4, shared prototype:
1
|
Child.prototype = Parent.prototype;
|
5, the use of temporary constructor:
1
2
3
|
var
Proxy =
function
() {};
Proxy.prototype = Parent.prototype;
Child.prototype =
new
Proxy();
|
6, extend replication property:
1
2
3
4
5
6
7
8
9
10
11
|
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 deep and shallow copy copy. 7, prototype inheritance patterns:
1
|
Object.create(Parent);
|
Two, Object.create inheritance
In this paper we learn about a seventh of inheritance Object.create () method to implement inheritance, a detailed description of this method, please stamp here . To learn to use the following method by several examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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: Benjamin
console.log(child.getName());
|
Let us look at an example, add an inheritance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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.com
console.log(SubChild.url);
//Outputs: zuojj
console.log(SubChild.getName());
//Outputs: undefined
console.log(Child.sex);
//Outputs: Benjamin
console.log(Child.getName());
|
通过上面可以看出Object.create()方法实现了链式继承,及原型链的继承。如果在控制台打印出各个生成的对象,可以很清楚的看到。
1
2
3
4
|
//Outputs: true
console.log(Child.isPrototypeOf(SubChild));
//Outputs: true
console.log(Parent.isPrototypeOf(Child));
|
isPrototypeOf() 方法测试一个对象是否存在于另一个对象的原型链上。 以上就是本文对Object.create方法的描述,文中不妥之处,还望批评指正。