面试遇到的一道题,以为自己掌握得很牢固,其实渣渣,现在回过头来总结一下。
定义两个类,vehicle类,car类,vehicle类有两个方法,drive方法和stop方法,car类的drive方法继承自vehicle,stop方法是自己的方法,如何实现。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
function Vehicle(){
this.drive = function(){
alert("vehicle-drive");
}
this.stop = function(){
alert("vehicle-stop");
}
}
function Car(){
//第一种方法,利用函数继承,是将整个函数赋给一个中间变量,然后执行这个方法,然后重写了stop函数。
// this.temp = Vehicle;
// this.temp();
//第三种方法,利用call或者apply,两者只是参数的形式不同。
Vehicle.call(this);
this.stop = function(){
alert("car-stop");
}
console.log(this);
}
//第二种方法,利用prototype继承
// Car.prototype = new Vehicle();
var car = new Car();
car.drive();
car.stop();
</script>
</html>
本文通过一个具体的JavaScript编程案例,展示了如何在一个子类中继承父类的方法并覆盖特定的行为。重点介绍了三种实现继承的方式:函数继承、原型链继承以及使用`call`或`apply`方法。

被折叠的 条评论
为什么被折叠?



