js原型继承

先说原型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Cat(name,color){
this.name = name;
this.color = color;
this.type = "猫科动物";
this.obj = {a:{b:1}}
this.eat = function(){console.log("吃老鼠");};
}
Cat.prototype.eat = function() {
console.log('吃大老鼠')
};
var cat1 = new Cat("大毛","黄色");
var cat2 = new Cat ("二毛","黑色");
console.log(cat1.obj); // 猫科动物
console.log(cat1.obj==cat2.obj)//false
console.log(cat1.eat==cat2.eat)//true
console.log(cat1,cat2)
console.log(Cat.prototype.constructor)

总结。为什么cat1.eat==cat2.eat 这就是传说中的new的时候做了什么。

一个继承的实现方式

1
2
3
4
5
6
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}

总结

原型继承博大精深,感觉prototype的设计是js继承的基础。没有prototype,js将不能在浏览器运行。关于prototype内部实现原理,还需要继续探索。