JavaScript高级(2)——继承

1、原型继承

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// 利用原型的特性实现继承
Student.prototype = new Person()

var s1 = Student('张三', 18)

console.log(s1.type) // => human

s1.sayName() // => hello 张三
	

缺点:无法设置构造函数的参数

2、构造函数的属性继承:借用构造函数

function Person (name, age,sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}
Person.prototype.sayHi=function(){
	console.log(this.name);
}
function Student (name, age,sex,score) {
  // 借用构造函数继承属性成员
  Person.call(this, name, age,sex);
  this.score = score;
}

var s1 = Student('张三', 18,'男',100)
console.log(s1.type, s1.name, s1.age);

缺点:不能继承父类原型里的属性方法继承。

3、组合继承:借用构造函数+原型继承

function Person(name,age,sesx){
	this.name = name;
	this.age = age;
	this.sex = sex;
}
Person.prototype.sayHi = function(){
	console.log('大家好,我是:'+this.name);
}
function Student(name,age,sex,score){
	//借用构造函数
	Person.call(this,anme,age,sex);
	this.score = score;
}	
//通过原型让子类型继承父类型中的方法
Student.prototype= new Person();
Student.proototype.constructor= Student;
var s1 = new Student ('zs',18,'男',100)

你可能感兴趣的:(JavaScript,javascript)