简单实现
//构造函数
function Dog (name){
this.name = name;
}
var husky = new Dog("哈士奇");
console.log(husky.name); //哈士奇
但是这种继承无法实现数据和方法的共享
//构造函数
function Dog (name){
this.name = name;
this.sound = "汪!~"
}
var husky = new Dog("哈士奇");
var alaska = new Dog("阿拉斯加");
//修改
Dog.sound = "汪汪汪!~";
console.log(husky.sound); //汪!~
console.log(alaska.sound); //汪!~
实例对象需要共享的属性和方法,放在prototype里面。不需要共享的属性和方法,就放在构造函数里面。
//构造函数
function Dog (name){
this.name = name;
}
Dog.prototype.sound = "汪!~";
var husky = new Dog("哈士奇");
var alaska = new Dog("阿拉斯加");
console.log(husky.sound); //汪!~
console.log(alaska.sound); //汪!~
Dog.prototype.sound = "汪汪汪!~";
console.log(husky.sound); //汪汪汪!~
console.log(alaska.sound); //汪汪汪!~
原型链继承
//构造函数
function Dog (name){
this.name = name;
}
Dog.prototype.sound = ["汪!~"];
function Husky (name){
this.name = "哈士奇";
}
function Alaska (name){
this.name = "阿拉斯加";
}
Husky.prototype = new Dog();
Alaska.prototype = new Dog();
var husky = new Husky();
console.log(husky.sound); //["汪!~"]
husky.sound.push("嗷呜!~");
console.log(husky.sound); //["汪!~","嗷呜!~"]
var alaska = new Alaska();
console.log(alaska.sound); //["汪!~","嗷呜!~"] <- ???
当原型内包含引用类型值时,子类实例husky对sound属性做出修改后,连其他子类也受到影响啦!
组合继承把需要被保护的数据放在构造函数,子类之间既能共享数据又能保证安全。
//构造函数
function Dog (name){
this.sound = ["汪!~"];
}
function Husky (name){
this.name = "哈士奇";
}
function Alaska (name){
this.name = "阿拉斯加";
}
Husky.prototype = new Dog();
Husky.prototype.constructor = Husky;
Alaska.prototype = new Dog();
Alaska.prototype.constructor = Alaska;
var husky = new Husky();
console.log(husky.sound); //["汪!~"]
husky.sound.push("嗷呜!~");
console.log(husky.sound); //["汪!~","嗷呜!~"]
var alaska = new Alaska();
console.log(alaska.sound); //["汪!~"]