释放双眼,带上耳机,听听看~!
1、
将父对象作为新对象的原型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 1function object(o) {
2 var n;
3 function F() {}
4 F.prototype = o;
5 n = new F();
6 n.uber = o;
7 return n;
8}
9
10var shape = {
11 name: 'Shape',
12 toString: function(){
13 if(this.uber)
14 return this.uber.toString() + ', ' + this.name;
15 else
16 return this.name;
17 }
18}
19var twoDShape = object(shape);
20twoDShape.name = "2 D Shape";
21alert(twoDShape.toString());
22
2、在子构造器中调用父构造器Parent.apply();并传递参数,这样与父对象的this绑定的属性同时成为子对象的属性
1
2
3
4
5
6
7
8
9
10
11 1function Shape(id) {
2 this.id = id;
3
4}
5Shape.prototype.name = 'shape';
6Shape.prototype.toString = function(){return this.name;};
7
8function Triangle() {
9 Shape.apply(this, arguments);//原生属性继承
10}
11