原型链的意思是 先找对应的对象看看对象中是否存在对应的某一个属性或方法,如果不存在时,那么再去找对应的原型上是否有对应的属性
//创建一个人类然后继承学生类以及教师类,分别通过三种不同的继承方式
function student(name,age){
this.name=name;
this.age=age;
}
function teacher(name,age){
this.name=name;
this.age=age;
}
teacher.prototype.work=function(){
console.log("正在教书");
}
//第一种继承 原型链继承:将原型改成对应的对象 缺点:无法初始化对应的属性
/*
function people(name,age){
}
people.prototype.work=function(){
console.log('我是学生');
}
people.prototype=new student("王一",21);
let d1=new people("王二",18)
console.log(d1);*/
//第二种继承:冒充继承法:通过call或者apply改变this指向实现的
//问题:无法将原型中所带有的方法和属性继承过来
/* function people(name,age){
this.man="王三"
teacher.call(this,name,age);
}
people.prototype.work=function(){
console.log('我是教师'+this.name);
}
let t=new people('小红',35);
t.work()
console.log(t);*/
//第三种继承:冒充继承+原型继承
function people(name,age){
teacher.call(this,name,age);
}
people.prototype=new teacher();
people.prototype.w=function(){
console.log(this.name+"正在吹水");
}
let c1=new people("小红",36);
console.log(c1);
c1.work()
//call方式使用
对象.call(this 改变this指向性,参数1,参数2);
举例:teacher.call(this,name,age);
//apply方式使用
对象.apply(this 改变this指向性,[参数1,参数2])
区别:call传入的是参数,apply传入的是数组
面向对象 set get 作用以及目的 如何实现私有属性
面向对象的编程特点
1.抽象性:通过对象分析具体问题
2.封装性:将属性和方法全部封装到对象中,便于维护和节约二次开发成本 安全
3.继承性:将对象直接属性或者方法 进行传递 java c python
4.多态性:一个类产生多种对象 js用不到
对象属性分为两种:一.公有属性:可以任意访问,修改的
二.私有属性 必须通过方法才能访问或者修改
(密码:需要一定安全性)
(需要一定校验规则)
案例:
function User(name,password,phonenumber){
var phonenumber=phonenumber;
this.name=name;
this.password=password;
this.imgUrl=""
//通过私有属性的访问方法和设置方法
this.getphonenumber=function(){
return phonenumber
}
//设置
this.setphonenumber=function(number){
let reg=/\d{11}$/
if(reg.test(number)){
phonenumber=number;
}else{
alert('格式不正确')
}
}
}
let u=new User('admin',123456,15767986932)
console.log(u.setphonenumber(15767985999));
console.log(u.phonenumber,u.getphonenumber());