Discuss / JavaScript / 这种继承方法肿么样?

这种继承方法肿么样?

Topic source

savokiss

#1 Created at ... [Delete] [Delete and Lock User]

继承

        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

kwyh

#2 Created at ... [Delete] [Delete and Lock User]

看起来不错的样子,验证了下貌似也可以。

吴双Shawn

#3 Created at ... [Delete] [Delete and Lock User]

我觉得这个跟前面同学说的方法是一样的, 也有相同的问题: subclass的原型上面挂了了一堆superclass的属性,不够优雅


  • 1

Reply