您的位置:首页 > Web前端 > JavaScript

Javascript 实现继承的三种方式

2015-01-07 22:10 585 查看
Javascript实现继承的三种方式:

1.使用apply

function Animal() {
            this.type = "动物";
}

function Cat(name, age) {
            Animal.apply(this, arguments);
            this.name = name;
            this.age = age;
}

var cat1 = new Cat("justin", 3);
alert(cat1.type);

结果是:



2.使用call方式

function Employee(name, age) {
            this.name = name;
            this.age = age;
}

function SuperEmployee(name, age, salary) {
            Employee.call(this, name, age);
            this.salary = salary;
}

var se = new SuperEmployee("justin", 25, 1000);
alert(se.name + se.age + se.salary);

结果:



3.使用property重定向

Cat.property = new Animal();
alert(Cat.property.constructor);
Cat.property.constructor = Cat
alert(Cat.property.constructor);

var cat2 = new Cat("dustin", 4);
alert(cat2.type);

结果是:



整个例子代码如下:

<script type="text/javascript">
        function Animal() {
            this.type = "动物";
        }

        function Cat(name, age) {
            Animal.apply(this, arguments);
            this.name = name;
            this.age = age;
        }

        var cat1 = new Cat("justin", 3);
        alert(cat1.type);

        Cat.property = new Animal();
        alert(Cat.property.constructor);
        Cat.property.constructor = Cat
        alert(Cat.property.constructor);

        var cat2 = new Cat("dustin", 4);
        alert(cat2.type);

        function Employee(name, age) {
            this.name = name;
            this.age = age;
        }

        function SuperEmployee(name, age, salary) {
            Employee.call(this, name, age);
            this.salary = salary;
        }

        var se = new SuperEmployee("justin", 25, 1000);
        alert(se.name + se.age + se.salary);

    </script>

Note:call和apply的区别在于传递参数的方式不同而已,apply的第二个参数是一个参数的数组,而call是逐个传参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: