方法一: (直接prototype等号赋值,缺点:地址相同)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数继承</title>
</head>
<body>
<script>
function p1(opt){
this.name = opt.name
this.age = opt.age
}
p1.prototype.sayName = function(){
console.log(this.name)
}
function p2(opt){
p1.call(this,opt)
this.sex = opt.sex
}
p2.prototype = p1.prototype
p2.prototype.sayAge = function(){
console.log(this.age)
}
const o2=new p2({
name:"蜘蛛侠",
age:"19",
sex:"man"
})
console.log(o2)
</script>
</body>
</html>
方法一 运行结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190709091927956.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjE0OTI4,size_16,color_FFFFFF,t_70)
方法二: (B.prototype = new A({}) 缺点:函数与声明的变量都赋值了)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数继承</title>
</head>
<body>
<script>
function p1(opt){
this.name = opt.name
this.age = opt.age
}
p1.prototype.sayName = function(){
console.log(this.name)
}
function p2(opt){
p1.call(this,opt)
this.sex = opt.sex
}
p2.prototype = new p1({})
p2.prototype.sayAge = function(){
console.log(this.age)
}
const o2=new p2({
name:"蜘蛛侠",
age:"19",
sex:"man"
})
console.log(o2)
</script>
</body>
</html>
方法二 运行结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190709092446347.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjE0OTI4,size_16,color_FFFFFF,t_70)
方法三: (方法1与2的结合,既不地址相同 也不继承不需要的属性)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数继承</title>
</head>
<body>
<script>
function p1(opt){
this.name = opt.name
this.age = opt.age
}
p1.prototype.sayName = function(){
console.log(this.name)
}
function p2(opt){
p1.call(this,opt)
this.sex = opt.sex
}
function c(){}
c.prototype = p1.prototype
p2.prototype = new c()
p2.prototype.sayAge = function(){
console.log(this.age)
}
const o2=new p2({
name:"蜘蛛侠",
age:"19",
sex:"man"
})
console.log(o2)
</script>
</body>
</html>
方法三 运行结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190709093303942.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjE0OTI4,size_16,color_FFFFFF,t_70)
方法四:(遍历需继承方法的prototype即可,但是.prototype.prototype继承不了)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js函数继承</title>
</head>
<body>
<script>
function p1(opt){
this.name = opt.name
this.age = opt.age
}
p1.prototype.sayName = function(){
console.log(this.name)
}
function p2(opt){
p1.call(this,opt)
this.sex = opt.sex
}
for(var key in p1.prototype){
p2.prototype[key] = p1.prototype[key]
}
p2.prototype.sayAge = function(){
console.log(this.age)
}
const o2=new p2({
name:"蜘蛛侠",
age:"19",
sex:"man"
})
console.log(o2)
</script>
</body>
</html>
方法四 运行结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190709093938828.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjE0OTI4,size_16,color_FFFFFF,t_70)