JS面向对象-封装,继承,多态。
1.封装:
1.1构造函数封装
通俗的来讲就是说我们有一些秘密不想让人知道。我们就需要通过私有化变量和私有化方法的形式,将函数封装起来。这样的话外界不能访问函数内部的私有化变量私有化方法;如果你有一些想让大家知道的东西,你就可以通过this在创建的属性看作是对象共有的属性和对象共有方法。这样别人就能知道你的公共的东西,不止如此你还可以访问到类或者对象自身的私有属性和私有方法。
var Book=function(id,name,price){
this.id=id;
this.name=name;
this.price=price;
}
/封装后
var Book=function(id,name,price){
/ 私有属性
var num=1;
/ 私有方法
function checkId();
var bookname='';
/ 特权方法
this.getName=function(){
return bookname;
};
this.getPrice=function(){};
this.setName=function(){
bookname=name
};
this.setPrice=function(){};
/ 对象公有属性
this.id=id;
/ 对象公有方法
this.aaa=function(){};
/ 构造器
this.setName(name);
this.setPrice(price);
}
var b=new Book(1,'Javascrpit 面向对象',8.9);
console.log(b.num);/undefined
console.log(b.id);/ id的值
console.log(b.setName('aaaaa'));
1.2.闭包实现封装
闭包是有权限访问另外一个函数作用域中变量的函数。也就是在一个函数内部创建另外一个函数。
闭包呢,是在一个函数内部创建一个新的函数。并且在函数的外部调用内部创建的新函数作用域内的变量或函数所构成的闭合区间。称之为闭包。
(function(){
/静态私有变量
var bookNum=0;
/ 静态私有方法
function checkBook(name){
/ 检查书的语言
}
/ 创建历史书籍类
function Book(newId,newName,newPrice){
/ 私有变量
var name,price;
/ 私有方法
var setName=function(name_){
name=`《${name_}》`;
}
var setPrice=function(price_){
price=Number(price)*2;
}
bookNum++;
if(bookNum>3){
new Error('我们仅出版3本书')
}
setName(newName);
setPrice(newPrice);
/ 特权方法
this.getName=function(){
name;
}
this.getPrice=function(){
price;
}
/ 公有属性
this.id=newId;
}
Book.prototype={
/ 静态公有成员属性
isBookType:'历史书'
}
})();