(1) 对象收编变量
例如简单的表单验证,我们会验证很多的东西,但是我们声明的很多变量,可能造成对原生对象,或者一些框架的污染,所以我们收编这些变量,污染就会相对的减少许多,我们就可以这个样子写
var cheakForm = {
cheakName:function(){//检验姓名
}
cheakPhone:function(){//检验手机号
}
}
(2) 我们在做面向对象编程的时候,应该要有类的思想,类里面会有一些成员方法,那我们怎么来调用来链式调用成员方法呢,return this
var Book = function(name,price){
this.name = name;
this.price = price;
this.readBook = function (){
console.log('我正在读这本书');
return this;
}
this.writeBook = function (){
console.log('我正在写这本书');
return this;
}
}
var book = new Book();
book.readBook();
book.writeBook();
book.readBook().writeBook(); //链式调用
(3)在类的封装中,我们也会有类的私有属性和公有属性,是通过变量的作用域来实现的,比如
var Book = function (name,price){
var name = name;
this.price = price;
this.readBook = function(){
console.log('正在读这本书');
}
var witeBook = function () {
console.log('正在写这本书');
}
}
var book = new Book ('历史',500)
console.log(book.name) //is undefined
console.log(book.price)
book.readBook();
book.witeBook(); //is not a function
(4) new关键字的作用可看做是对当前的this不停地赋值,若不用this,则函数在全局中被执行.若我们在实例化类的时候忘记使用new怎么办呢,我们可以使用安全模式,来保证我们的类的实例化
var Book = function(name,price){
if(this instanceof Book){
this.name = name;
this.price = price;
this.readBook = function (){
console.log('我正在读这本书');
return this;
}
}
else{
return new Book(name,price);
}
}
(5) 类的继承,如何继承 A类.prototype = B类 ====> A继承了B; (实例化A后,共享B的成员属性和方法,一个改变都会改变),通过构造函数的方法来继承就不会共享,而是单独拥有一份B的属性和方法
//构造函数的方法来继承 每个实例都单独拥有一份,而不能共有,违背了不能复用的原则
var Book = function(){
this.arr = [1,2,3]
}
var book = function (){
Book.call(this);
}
var book1 = new book ();
var book2 = new book ();
book1.arr.push('历史');
console.log(book1.arr); //[1,2,3,'历史']
console.log(book2.arr); //[1,2,3]
//组合式继承
var Book = function(name){
this.name = name
this.arr = [1,2,3]
}
var book = function (name){
Book.call(this,name);
}
Book.prototype.getName = function (){
console.log(this.name);
}
book.prototype = new Book();
var book1 = new book ('历史');
var book2 = new book ('政治');
book1.arr.push('历史');
console.log(book1.arr); //[1,2,3,'历史']
console.log(book2.arr); //[1,2,3]
book1.getName(); //历史
book2.getName(); //政治
(6)寄生式继承和单继承,多继承的原理机制
//过渡函数对象
function inheritObject (o){
function F(){};
F.property = o;
return new F();
}
//寄生式继承
function createBook(obj){
var o = new inheritObject(obj);
o.getName = function(){
console.log(name);
}
return 0;
}
//单继承
var extend = function (target,source) {
for(var property in source)
{
target[property] = source[property];
}
return target;
}
//多继承
var mix = function(){
var i = 1;
len = arguments.length;
target = arguments[0];
arg;
for(;i<len;i++)
{
arg = arguments[i];
for(var property in arg)
{
target[property] = arg[property];
}
}
return target;
}