JavaScript基于原型的继承

时间:2023-03-09 18:06:24
JavaScript基于原型的继承

在一个纯粹的原型模式中,我们会摒弃类,转而专注于对象,基于原型的继承相比基于类的继承的概念上更为简单

if( typeof Object.beget  !== 'function')
{
Object.beget = function(o) {
var F = function() {};
F.prototype = o;
return new F();
}
}
var myMammal = {

      name : 'Herb the Mammal',
get_name : function() {
return this.name;
},
says : function() {
return this.saying || ' ';
}
};
var myCat = Object.beget(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.get_name = function() {
return this.says + ' '+ this.name + ' '+this.says;
};