JavaScript继承

面向对象编程: 三个特征,封装、继承、多态。
封装: 把客观事物封装成抽象的类。
继承: 通过基类生成子类(类与类的操作).子类具有基类的所有属性和方法,并能进行扩展。
1.封装
学生类

function Student(name){
	this.name = name;
}
Student.prototype.study = function(course){
	console.log(this.name + ' study ' + course);
};

JavaScript实现继承有两种方式:类式继承和原型继承
1.类式继承
类式继承是JavaScript继承的主要模式,几乎所有面向对象方式编写的JavaScript代码都用到了类式继承。在各种流行语言中只有JavaScript使用原型式继承,所以最好使用类式继承。
下面是具体代码:

 // 封装基类
function Person(name){
    this.name = name;
    this.sexList = ['female', 'male'];
}
// 给这个超类的原型上添加方法
Person.prototype.say = function(){
    console.log(this.name + ' say!');
};

// 封装子类
function Student(name, age){
    Person.call(this, name); 
    this.age = age;
}
// 子类继承基类
Student.prototype = new Person(); // 进行基类原型的继承
Student.prototype.constructor = Student;
Student.prototype.study = function(course){
    console.log(this.name + ' study ' + course);
};
var b = new Student('john', 20);
b.say();
b.study('math');

上述代码,首先创建了一个基类,然后创建子类,子类继承基类。
注意两个容易忽略的地方:
a).创建子类的时候

Person.call(this, name);

这句话的作用是进行基类构造函数的继承
b).创建子类的时候

Student.prototype.constructor = Student;

因为Student.prototype = new Person(); 所以Student.prototype.constructor指向Object.
下面看一个例子:

function Person(name){
    this.name = name;
    this.sexList = ['female', 'male'];
}

Person.prototype.say = function(){
    console.log(this.name + ' say!');
};
var xiaoming = new Person();
console.log(xiaoming.constructor); // function Person(name){...}
Person.prototype = {
    paws:4
};
var newPerson = new Person();
console.log(newPerson.constructor); // function Object(){...}

2.原型式继承

// 创建基础对象
var Person = {
    name: 'default',
    list: [1, 2, 3],
    say: function(){
        console.log(this.name + ' say!');
    }
};
var clone = function(obj) {
    var newObj = function(){};
    newObj.prototype = obj;
    return new newObj;
};
var xiaoming = clone(Person);
xiaoming.name = 'xiaoming';
xiaoming.list[0] = 0;
xiaoming.career = 'student';
xiaoming.say(); // xiaoming say!
console.log(xiaoming.list, xiaoming.career); // [0, 2, 3] student
var john = clone(Person);
john.name = 'john';
john.list[0] = 4;
john.career = 'teacher';
john.say(); // john say!
console.log(john.list, john.career); // [4, 2, 3] teacher

参考文章:
前端攻略系列(三) – javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
JS–继承(原型式继承和寄生继承)

此条目发表在JavaScript分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注