Object对象是顶级父类它的原型中的方法和属性任何对象都可以调用,例如toString就是Object的方法。
继承的三种方式:
1.组合继承
var Person = function(name,age){
this.name = name;
this.age = age;
}
Person.prototype = {
say : function(){
console.log('Person.prototype - say');
}
}
function Teatcher(name,age,sex){
this.sex = sex;
//指向基类构造函数
Person.call(this,age,sex);
}
/*Teatcher.prototype = new Person();
Teatcher.prototype.constructor = Teatcher;或者*/
Teatcher.prototype.__proto__ = Person.prototype;
Teatcher.prototype.giveClass = function(){
console.log('Teatcher.prototype - giveClass');
}
var cher = new Teatcher("老胡",54,"boy");
cher.say();
cher.giveClass();
console.log(cher);

2.寄生组合继承 把父类的原型赋值给子类的原型
/*继承的固定函数-父原型赋值给子原型并改变constructor*/
function inheritPrototype(subType,superType){
var prototype = superType.prototype;
prototype.constructor = subType;
subType.prototype = prototype;
}
function Person(name){
this.name = name;
}
Person.prototype = {
say : function(){
console.log('Person.prototype - say');
}
}
function Student(name,age){
Person.call(this,name);
this.age = age;
}
inheritPrototype(Student,Person);
Student.prototype.giveClass = function(){
console.log('Teatcher.prototype - giveClass');
}
var xiaozhang = new Student('小张',20);
console.log(xiaozhang.name);
xiaozhang.say();
xiaozhang.giveClass();
console.log(xiaozhang);

3.拷贝继承 把父类的属性和方法拷贝给子类
var Chinese = {nation:'中国'};
var Doctor ={career:'医生'}
// 请问怎样才能让"医生"去继承"中国人",也就是说,我怎样才能生成一个"中国医生"的对象?
// 这里要注意,这两个对象都是普通对象,不是构造函数,无法使用构造函数方法实现"继承"。
function extend(p) {
var c = {};
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
return c;
}
var Doctor = extend(Chinese);
Doctor.career = '医生';
alert(Doctor.nation); // 中国
网友评论