js 类的继承
- 方法一:
通过使用构造函数,prototype,inherit 和 method 方法来实现类的继承;
1 |
|
- 方法二:
把原型放到一个对象中做为类,然后通过 create 方法来实例化,通过 extend 来创建子类;
这种方法的好处是可以忽略 prototype 的使用;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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66//定义 extend 和 create 方法
// 给对象定义了一个 create 方法,该方法使得对象可以复制一个子对象出来;并且这个子对象还会
// 根据传入的参数,调用继承自父对象的 construct 方法,进行自己的初始化;
Object.prototype.create = function(){
var object = clone(this);
if (object.construct != undefined)
object.construct.apply(object, arguments);
return object;
}
// 给对象定义了一个 extend 方法,该方法会创建一个子对象,并将传入的对象的所有属性,复制一份到子对象上;
Object.prototype.extend = function(properties){
var result = clone(this);
forEachIn(properties, function(name, value){
result[name] = value;
});
return result;
}
//写个相同的例子
var Item = {
construct: function(name){
this.name = name;
},
inspect: function(){
alert("It is " + this.name + ".");
},
kick: function(){
alert("Klunk!");
},
take: function(){
alert("You cannot lift " + this.name + ".");
}
}
var lantern = Item.create("the brass lantern");
var DetailedItem = Item.extend({
construct: function(name, details){
Item.construct.call(this, name);
this.details = details;
},
inspect: function(){
alert("you see " + this.name + "," + this.details + ".");
}
});
var giantSloth = DetailedItem.create("the giant sloth",
"it is quietly hanging from a tree, munching leaves");
var SmallItem = Item.extend({
kick: function(){
alert(this.name + " files across the room.");
},
take: function(){
alert("you take " + this.name + ".");
}
});
var pencil = SmallItem.create("the red pencil");
pencil.take();
总结:不管是第1种的 inherit 方法,还是第二种的 create 方法,它们都是通过将父对象做子对象的原型来实现的继承,区别在后者对 prototype 的使用进行了封装,不需要老是打 protoype 这个单词, 降低了出错概率,更好的实现了概念的抽象;
js 类的继承
https://ccw1078.github.io/2017/11/12/js 类的继承/