NO4 ES5中的类和继承

66 阅读1分钟
// NO1 es5的类--------------------------

        /** function Person() {

            this.name = "张三"

            this.age = 20

            this.run = function () { // 实例方法

                alert(this.name + '在运动')

            }

        }

        Person.say = function () {

            alert('我是静态方法')

        }

        // 原型链上面的属性会被多个实例共享, 构造函数不会 ?

        Person.prototype.sex="男"

        Person.prototype.work = function () {

            alert(this.name + '在工作')

        }

        var p = new Person()

        // alert(p.name)

        // p.run()

        // p.work()

        Person.say() */

        // NO2 es5的对象冒充继承和原型链继承-------------------------- 

        /**

         * function Person() {

                this.name = "张三"

                this.age = 20

                this.run = function () {

                    alert(this.name + '在运动')

                }

            }

            Person.prototype.sex="男"

            Person.prototype.work = function () {

                alert(this.name + '在工作')

            }

         * */ 

            // 对象冒充实现继承,可以继承构造函数里面的属性和方法,但无法继承原型链上面的属性和方法

            /**

             *  function Web() {

                    Person.call(this)

                }

                var w = new Web()

                w.run() // 正确执行

                w.work() // w.work is not a function

            */

            // 原型链实现继承,既可以继承构造函数里面的属性和方法,也可以继承原型链上面的属性和方法

            /**

             * function Web() {

                }

                Web.prototype = new Person()

                var w = new Web()

                w.run() // 正确执行

                w.work() // 正确执行

            */

        // NO3 上述的原型链继承无法给父类传参,需要组合继承(原型链 + 对象冒充)

        function Person(name, age) {

            this.name = name

            this.age = age

            this.run = function () {

                alert(this.name + '在运动')

            }

        }

        Person.prototype.sex="男"

        Person.prototype.work = function () {

            alert(this.name + '在工作')

        }



        function Web(name,age) {

            Person.call(this, name, age) // 继承构造函数里面的属性和方法

        }

        // Web.prototype = new Person()

        Web.prototype = Person.prototype // 继承父类的原型链



        var w = new Web('赵四',22)

        w.run()

        w.work()