- 面向对象
将需求抽象成一个对象,然后针对该对象分析其属性和方法。
var Book = function(id,bookname,price){
this.id = id;
this.bookname = bookname;
this.price = price;
}
- 闭包
在一个函数内部创建另外一个函数。
var Book = (function(){
var bookNum = 0;
function checkBook(name){}
function _book(newid,newName,newPrice){
var name;
var price;
function checkId(id){};
this.getName = function(){}
this.getPrice = function(){}
this.setName = function(){}
this.setPrice = function(){}
this.id = newid;
this.copy = function(){}
bookNum++;
if(bookNum >100){
throw new Error('我们仅出版100本书。');
}
this.setName(name);
this.setPrice(price);
}
_book.prototype = {
isJSBook : false,
diisplay : function(){}
};
return _book;
})();
- 创建对象的安全模式
为了避免创建对象的时候遗忘掉new关键字,我们可以在程序里面控制
var Book = function(title,time,type){
if(this instanceof Book){
this.title = title;
this.time = time;
this.type = type;
}else{
return new Book(title,time,type);
}
}
- 继承
1,子类的原型对象—类式继承
实现方式:将父类的实例赋给子类的原型。
其实这种实现方式,本质上式子类的原型继承了父类
缺点:子类通过其原型对父类进行实例化,继承了父类。父类的公共属性要是引用类型,这样就被所有的子类所共有。
2,创建即继承 —构造函数继承
//父类
function SuperClass(id){
this.books = {'javascript','html','css'};
this.id = id;
}
SuperClass.prototype.showBooks = function(){
console.log(this.books);
}
//子类
function SubClass(id){
SuperClass.call(this,id);
}
call方法改变了函数的作用环境。
缺点:没有使用到prototype,无法继承原型方法。
3,取其优点 – 组合继承
//父类
function SuperClass(id){
this.books = {'javascript','html','css'};
this.id = id;
}
SuperClass.prototype.showBooks = function(){
console.log(this.books);
}
//子类
function SubClass(id){
SuperClass.call(this,id);
}
SubClass.prototype = new SuperClass();
同构造函数继承方式,最后加上,将父类的实例赋给子类的原型。
缺点:我们调用了两次父类的构造函数,这并不完美。
4,洁净的继承者 – 原型式继承
//原型式继承
function inheritObject(o){
function F(){}
F.prototype = o;
reutrn new F();
}
var book = {
name:"js book",
alikeBook:{"css book","html book"}
};
var newBook = inheritObject(book);
这种继承,利用过渡函数F来实现
今天先写到这里,明天接着写