GemaGemaGema js继承

1.寄生组合式继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function inheritPrototype(subType,superType){
var prototype = Object(superType.prototype);
prototype.construction = subType;
subType.prototype = prototype;
}
function SuperType(name){
this.name=name;
this.colors = ["r","y","g"];
}
SuperType.prototype.sayName = function(){
console.log(this.name);
}
function Subtype(name,age){
SuperType.call(this,name);
this.age = age;
}
inheritPrototype(Subtype,SuperType);

2.寄生式继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function object(o){
function F(){};
F.prototype = o;
return new F();
}
function createAnother(original){
var clone = object(original);
clone.sayHi = function(){
console.log("hi")
}
return clone;//返回对象
}
var person = {
name : "jiji",
friends : ["lili","vivi"]
}
var anotherPersson = createAnother(person);
anotherPersson.sayHi();

3.原型式继承

1
2
3
4
5
6
7
8
9
10
11
12
function object(o){
function F(){};
F.prototype = o;
return new F();
}
//object()对传入其中的对象执行了浅复制
var person = {
name:"jiji",
colors:["a","b","c"]
}
var anotherPersson = object(person);
anotherPersson.name = "lily";

或者使用Object.create();

1
2
3
4
5
6
var person = {
name:"jiji",
colors:["a","b","c"]
}
var anotherPersson = Object.create(person);
anotherPersson.name = "lily";

4.组合继承(原型链+构造函数)

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
function SuperType(name){
this.name = name,
this.colors = ["c","b","a"]
}
SuperType.prototype.sayName = function(){
console.log(this.name);
}
function SubType(name,age){
//继承属性
SuperType.call(this,name);
this.age = age;
}
//继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
console.log(this.age)
}
var p1 = new SubType("jiji","18");
p1.colors.push("111");
console.log(p1.colors);//["c", "b", "a", "111"]

var p2 = new SubType("lili","28");
p2.colors.push("222");
console.log(p2.colors);//["c", "b", "a", "222"]

5.原型链

1
2
3
4
5
6
7
8
9
10
11
12
13
function SuperType(){
this.name = "jiji",
this.colors = ["c","b","a"]
}
SuperType.prototype.sayName = function(){
console.log(this.name);
}
function SubType(name){
this.namenn = "lili"
}
SubType.prototype = new SuperType();
var s1 = new SubType();
s1.sayName();//jiji

6.构造函数

1
2
3
4
5
6
7
8
9
10
11
12
function SuperType(){
this.name = "jiji",
this.colors = ["c","b","a"]
}
SuperType.prototype.sayName = function(){
console.log(this.name);
}
function SubType(name){
//继承属性
SuperType.call(this);
}
var s1 = new SubType();