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