标签:span pre app 真心 const code function blog tor
网上一查,肯定搜索到继承的文章真心不少。我这里就只说一下自己常用的方式:
通常 在编写一个类的做法是,在构造函数里声明字段,在prototype里指定方法。
//step1: 在子类的构造器里法里实例call ,apply 来继承字段
//step2: 类声明完毕后,使用inheritsPrototype来继承方法
function inheritsPrototype(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() {}; F.prototype = baseClazz.prototype; clazz.prototype = new F(); for (var prop in clazzPrototype) { clazz.prototype[prop] = clazzPrototype[prop]; } // clazz.prototype.constructor = clazz; // clazz.superClass = baseClazz; }
demo:
function inheritsPrototype(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() {}; F.prototype = baseClazz.prototype; clazz.prototype = new F(); for (var prop in clazzPrototype) { clazz.prototype[prop] = clazzPrototype[prop]; } } function A(id, name){ this.id = id; this.name = name; } A.prototype.show = function (){ console.log(this.id, this.name); } function B(id, name, age){ A.call(this, id, name); // 继承字段 this.age = age; } inheritsPrototype(B, A); // 继承方法 var objB = new B("x01", "name1", 12); objB.show();
标签:span pre app 真心 const code function blog tor
原文地址:http://www.cnblogs.com/f1194361820/p/7447587.html