JavaScript 继承
JavaScript继承 即子类继承父类 以对象型产生的,有五种方式:原型继承,原型链继承,混合继承,apply()方法继承,call()方法继承。
原型继承的特点:只有继承
function(){(空)}
用xx.prototype.xx=…;
混合继承的特点:继承+构造函数
继承:prototype,apply,call (apply,call 使用替换对象的方法)
call的语法规则 call(替换对象,参数列表)
apply的语法规则 apply(替换对象,[参数列表]) 参数列表是数组型写法
举例:
call
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>call的使用方法</title>
<script>
function per(){
this.name="张三";
this.sex="男";
this.bige="big";
this.way=function (name,sex,eye){
this.name=name;
this.sex=sex;
this.bige=eye;
}
}
function stu(){
}
var p=new per();
var s=new stu();
p.way.call(s,"李四","女","small");/*call(替换的对象,参数列表)*/
console.log(s);
</script>
</head>
<body>
</body>
</html>
apply
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>apply 的使用方法</title>
<script>
function per(){
this.name="张三";
this.sex="男";
this.bige="big";
this.way=function (name,sex,eye){
this.name=name;
this.sex=sex;
this.bige=eye;
}
}
function stu(){
}
var p=new per();
var s=new stu();
p.way.call(s,["李四","女","small"]);/*apply(替换的对象,[参数列表])*/
console.log(s);
</script>
</head>
<body>
</body>
</html>
继承第一种 追加继承的相关属性以及方法
eg.
<!DOCTYPEhtml>
<html>
<headlang="en">
<metacharset="UTF-8">
<title></title>
<script>
function per_son(){
this.name="李四";
this.sex="男";
this.bige="big";
this.height="200";
this.sayway=function (){
}
}
per_son.prototype.height="200";
per_son.prototype.sayway=function (){
console.log(this.bige);
}
//用法
/*创建实例对象在去调用继承方法*/
var per=new per_son();
per.sayway();
console.log(per.height);
</script>
</head>
<body>
</body>
</html>
继承第二种 两个构造函数之间相互继承
eg.
<!DOCTYPEhtml>
<html>
<headlang="en">
<metacharset="UTF-8">
<title></title>
<script>
function per_son(){
this.name="李四";
this.sex="男";
this.bige="big";
this.height="200";
this.sayway=function (){
}
}
function someone(){
}
someone.prototype=new per_son();
//两个构造函数之间的相互调用
var one=new someone();
one.sayway();
one.height
one.name
</script>
</head>
<body>
</body>
</html>
继承第三种 原型链继承
eg.
<!DOCTYPEhtml>
<html>
<headlang="en">
<metacharset="UTF-8">
<title></title>
<script>
function per_son(){
this.name="李四";
this.sex="男";
this.bige="big";
this.height="200";
this.sayway=function (){
}
}
//原型链继承
per_one.prototype=new per_son();
var per=new per_one();
console.log(per.bige);
</script>
</head>
<body>
</body>
</html>
自启函数:自动调用匿名函数
(function(){
alert();
})();//这个括号代表自己运行自己