1.三种不同的继承方式
<script type="text/javascript">
// 需要继承的
function Humanity(name,age){
this.name=name;
this.age=age;
}
Humanity.prototype.breathe=function(){
console.log(this.name+"正在呼吸")
}
//使用原型链继承创建教师类
//第一种继承方式:原型链继承
//问题:无法进行属性的更改 ,只有在继承时更改了一次
function tencher(name,age){
}
//将Humanity对象挂载到tencher原型上
tencher.prototype=new Humanity("老李",48);
tencher.prototype.lecture=function(){
console.log(this.name+"正在讲课")
}
var t1 = new tencher("老王",40);//无法进行属性的更改
console.log(t1);
console.log(t1.name);
t1.lecture();
t1.breathe();
//使用冒泡继承法创建学生类类
//第二种继承方式:冒充继承法
// 问题:无法将原型同时继承过来
//通过call或者apply改变this的指向性 ,直接讲构造函数在内部使用
function student(name,age){
//通过call或者apply改变this的指向性 ,直接讲构造函数在内部使用
Humanity.call(this,name,age)
}
student.prototype.attendclass=function(){
console.log(this.name+"正在听课")
}
var s1 = new student("小王",18);
console.log(s1);
console.log(s1.name);
s1.attendclass();
// 无法将原型同时继承过来 报错
// s1.breathe();
//三组合继承方式:原型链继承+冒充继承
function chef(name,age){
//通过call或者apply改变this的指向性 ,直接讲构造函数在内部使用
Humanity.call(this,name,age)
}
//将Humanity对象挂载到chef原型上
chef.prototype=new Humanity();
chef.prototype.Cook=function(){
console.log(this.name+"正在做饭")
}
var c1 = new chef("张师傅",28);
console.log(c1);
console.log(c1.name);
c1.Cook();
c1.breathe();
</script>
2.原型链图
3.call(),apply()
call与apply都属于Function.prototype的一个方法,它们的作用一样,只是使用方式不同
作用
他们两个的作用是一样的都是为了改变this指向
区别
他们的区别就是接收参数的方式不同
call():传递给函数的参数需要列举出来
apply():传递给函数的是参数数组
var arr=[5,2,3,1,9,20,38] ;
var max1 = Math.max.apply(Math,arr);
console.log(max1);//38
var max2 = Math.max.call(Math,5,2,3,1,9,20,38);
console.log(max2);//38
var min1 = Math.min.apply(Math, arr);
console.log(min1);//1
var min2 = Math.min.call(Math,5,2,3,1,9,20,38);
console.log(min2);//1
4.面向对象 set get 作用以及目的 如何实现私有属性
面向对象编程特点
1.抽象性: 通过对象来分析具体的问题
2.封装性: 将属性和方法都封装到对象中,方便统一管理 便于维护 便于二次开发 安全性较高(私有)
3.继承性: 将对象的属性和方法进行传递 ,Java C C++
4.多态性: 一个类 可以产生多种对象!js用不了!!
封装性:面向对象 可以将属性 分为两大类
公开属性:
在任何位置都可以随便访问和修改 ,修改过程中没有任何的限制
私有属性:
不能随意访问,必须通过指定的方法来访问和修改
什么时候用到私有属性呢?
1.安全系数较高的属性 2.设置时不能随意设置 时用到私有属性
如何实现私有属性?
function identity(name,age,QQ){
var QQ=QQ;
this.name=name;
this.age=age;
//get方法来获取
this.getQQ=function(){
return QQ;
}
//set方法来设置
this.setQQ=function(gold){
var reg=/\d{8}/;
if(reg.test(gold)){
QQ=gold;
}else{
alert("必须八位数字");
}
}
}
var i1=new identity("艾伦",18,"123456");
console.log(i1.getQQ());
// 更改i1的QQ
i1.setQQ(152335678);
console.log(i1.getQQ());