原生js实现继承
程序员文章站
2022-04-23 15:36:34
在多数语言中继承都很重要。JavaScript是一个基于原型的语言,这意味着对象可以直接从其他对象继承。以下列出几种常见的js继承方式。 原型链继承 function Father(){ this.status = true; } Father.prototype.getSuper = functi ......
在多数语言中继承都很重要。javascript是一个基于原型的语言,这意味着对象可以直接从其他对象继承。以下列出几种常见的js继承方式。
-
原型链继承
function father(){ this.status = true; } father.prototype.getsuper = function(){ return this.status; }; function son(){ this.substatus = false; } //继承了 supertype son.prototype = new father(); son.prototype.getsub = function (){ return this.substatus; }; var instance = new son(); alert(instance.getsuper()); //true
-
借用构造函数继承
function father(){ this.colors = [1,2,3]; } function son(){ //继承了 father father.call(this); } var instance1 = new son(); instance1.colors.push(4); alert(instance1.colors); //"1,2,3,4" var instance2 = new son(); alert(instance2.colors); //"1,2,3"
-
组合继承
function father(name){ this.name = name; } father.prototype.sayname = function(){ alert(this.name); }; function son(name, age){ //继承属性 supertype.call(this, name); this.age = age; } son.prototype = new father(); //将子类的原型指向父类 son.prototype.constructor = son; //将子类的constructor指向自己 son.prototype.sayage = function(){ alert(this.age); }; var instance = new son("lh", 19); instance1.sayname(); //"lh"; instance1.sayage(); //19
-
原型式继承
function object(o){ function f(){} f.prototype = o; return new f(); } var person = { name: "lh", loves: ["a", "b", "c"] }; var anotherperson = object(person); anotherperson.name = "greg"; anotherperson.friends.push("d"); alert(person.loves); //"a,b,c,d"
这里的object方法和object.create()方法类似。
-
寄生式继承
function object(o){ function f(){} f.prototype = o; return new f(); } function createanother(obj){ var clone = object(obj); //通过调用函数创建一个新对象 clone.say = function(){ //给这个对象添加方法 alert("hi"); }; return clone; //返回这个对象 } var person = { name: "lh", loves: ["a", "b", "c"] }; var anotherperson = createanother(person); anotherperson.say(); //"hi"
-
寄生组合式继承
function inheritprototype(son, father){ var prototype = object.create(father.prototype); son.prototype = prototype;
prototype.constructor = son; } function father(name){ this.name = name; } father.prototype.sayname = function(){ alert(this.name); }; function son(name, age){ father.call(this, name); this.age = age; } inheritprototype(son, father); -
使用es6实现
class father{ constructor(x, y) { this.x = x; this.y = y; } } class son extends father{ constructor(x, y, age) { super(x, y); // 调用父类的constructor(x, y) this.age= age; } tostring() { return this.color + ' ' + super.tostring(); // 调用父类的tostring() } }
子类继承父类中constructor中必须先调用super()方法才能访问this,否则会报错。
上一篇: 俏皮可爱小孩子,各种生活现状图片集
下一篇: 超强防护套装