Javascript 实现继承的三种方式

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是逐个传参数。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值