方法一: (直接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>
方法一 运行结果如下:
方法二: (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>
方法二 运行结果如下:
方法三: (方法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>
方法三 运行结果如下:
方法四:(遍历需继承方法的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>
方法四 运行结果如下: