prototype和__proto__的区别
prototype是构造函数的一个属性
__proto__指向的就是对象构造函数的prototype
prototype实现继承
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15function Animal(){
this.name="animal"
this.eat=function(e){
console.log(e)
}
}
function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
构造函数实现继承
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17function Animal(){
this.name="animal"
this.eat=function(e){
console.log(e)
}
}
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.eat('fish'));
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true