call继承父级属性,prototype继承父级方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
</body>
<script type="text/javascript" >
// 通过call继承父级属性
function A(){
this.abc=12
}
function B(){
// this → new B();
A.call(this)
}
var obj = new B();
alert(obj.abc) //12
// 通过prototype继承父级方法
A.prototype.show=function(){
alert(this.abc)
}
B.prototype.show=A.prototype.show; //通过 prototype原型继承父级方法
obj.show() //12
</script> </html>
有先后顺序 先 继承 属性 再方法 否者 报错 说 那个 .call() 继承没有 这个 function
综合实例
实现效果 car.getInfo() 打印出 'car has 2 doors'
涉及到的知识点 继承 和 修改继承到的 属性以及方法
function vehicle(){ this.door=4; } function car (){ } vehicle.prototype ={ getName: function(){ return 'vehicle' }, getInfo: function(){ return [ this.getName(),'has',this.door,'doors' ].join(',') } }
结果
car.prototype = new vehicle(); // car 继承 wehicle 原型 的方法 var car1 = new car(); // 实例化 car1.door=2;//修改 原型值 car1.getName=function (){ //修改 vehicle 原型中的 getName 方法 return 'car' } console.log(car1.getInfo()) //实现效果 car.getInfo() 打印出 'car has 2 doors'


浙公网安备 33010602011771号