function inherit(subClass,superClass){ //兼容ES5以下 if(!Object.create){//兼容ES5以下 Object.create = function(proto){ function F(){} F.prototype = proto; return new F; } } //实现继承 subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; }
function Person(name,age){ this.name = name; this.age = age; } function Student(name,age,className){ Person.call(this,name,age); this.className = className; } inherit(Student,Person);//无此句最后一个将为false var stu = new Student('jason',24,'Grade 2'); console.log(stu.name);//jason console.log(stu.age);//24 console.log(stu.className);//Grade 2 console.log(stu instanceof Student);//true console.log(stu instanceof Person);//true
看起来不错的样子,验证了下貌似也可以。
我觉得这个跟前面同学说的方法是一样的, 也有相同的问题: subclass的原型上面挂了了一堆superclass的属性,不够优雅
Sign in to make a reply
savokiss
继承
实例