JavaScript的继承(Inheritance):js是一门基于原型的语言,这意味着对象直接从其他对象继承(来自JavaScript语言精粹)。
1.对象冒充:将子类对象先当成父类对象进行构造(绑定父类的属性),再绑定子类特有的属性。
function Person (name) {
this.name = name;
this.eat = function (){};
}
function Student (name, grade) {
this.method = Person;
this.method(name);
delete this.method;
this.grade = grade;
this.study = function () {};
}
2.call或apply方式
function Teacher (name, title) {
Person.call(this, name);
this.title = title;
}
3.原型链:所有函数对象都具有原型属性,该属性引用了堆空间中的原型对象,所有的对象都包含一个隐式的引用__proto__,用来指向在对象生成过程中所使用的构造函数的原型对象。
function Farmer (name, plant) {
this.name = name;
this.plant = plant;
}
Farmer.prototype = new Person();
Farmer.prototype.constructor = Farmer;
Farmer.prototype.doFarmWork = function (){};
4.函数化:可以让对象拥有私有属性和私有方法
var mammal = function (spec) {
var that = {};
that.get_name = function () {
return spec.name; //私有属性
}
that.says = function () {
return spec.saying || ''; //私有属性
}
return that;
};
var cat = function (spec) {
spec.saying = spec.saying || 'meow';
var that = mammal(spec);
that.purr = function () {};
that.get_name = function () {};
};
var myCat = cat({name : 'Henrietta'});