// 父类
function Person(name) {
this.name = name;
this.showName = function () {
console.log(this.name);
}
}
// 子类
function Staff(office) {
this.office = office;
this.showOffice = function(){
console.log(this.office);
}
}
Staff.prototype = new Person('staff');
const a = new Staff('D302');
const b = new Staff('D232');
a.showName(); // satff
a.showOffice(); // D302
b.showName(); // staff
b.showOffice(); // D232
Staff.prototype = new Person('staff');
const a = new Staff('D302');
const b = new Staff('D232');
a.name = 'change'
a.showName(); // change
b.showName(); // staff
Staff.prototype = new Person([1,2,3]);
const a = new Staff('D302');
const b = new Staff('D232');
a.showName(); // [1,3]
b.showName(); // [1,3]
a.name.push(4);
a.showName(); // [1,3,4]
b.showName(); // [1,4]
a.name = [1,2]
a.showName(); // [1,2]
b.showName(); // [1,4]
-
2. 不能向父类型的构造函数中传递参数
3. 只能继承一个父类
function Staff(name,office) {
Person.call(this,name);
this.office = office;
this.showOffice = function(){
console.log(this.office);
}
}
const a = new Staff('a','D302');
const b = new Staff('b','D232');
a.showName(); // a
b.showName(); // b
console.log(a instanceof Person); // false
- 可以向父类传递参数
- 可以实现多父类继承
- 父类的属性不会被子类共享
function Staff(name,name);
this.office = office;
this.showOffice = function(){
console.log(this.office);
}
}
Staff.prototype = new Person();
const a = new Staff('a','D232');
a.showName(); // a
b.showName(); // b
console.log(a instanceof Person); // true
- 继承前两者的优点
- 可以实现对构造函数的复用
function container(obj){
function F() {}
F.prototype = obj;
return new F();
}
const child = new Person('child');
const staff = container(child);
staff.showName(); // child
function container(obj){
function F() {}
F.prototype = obj;
return new F();
}
function Staff(obj,office) {
const sub = container(obj);
sub.office = office;
sub.showOffice = function(){
console.log(this.office);
}
return sub;
}
const child = new Person('child');
const a = Staff(child,'D232');
const b = Staff(child,'C433');
a.showName(); // child
a.showOffice(); // D232
b.showName(); // child
b.showOffice(); // C433
function Staff(name,name);
this.office = office;
this.showOffice = function () {
console.log(this.office);
}
}
Staff.prototype = Object.create(Person.prototype);
Staff.prototype.constructor = Person;
const a = new Staff('a','D232');
const b = new Staff('b','C433');
a.showName(); // a
a.showOffice(); // D232
b.showName(); // b
b.showOffice(); // C433