1.用对象收编变量(函数) 这里myFun是对象无法new
var myFun = {
fun1:function(){
console.log(1);
},
fun2:function(){
console.log(2);
}
}
myFun.fun1();//用点语法来使用函数
2.用点语法创建函数 无法new复制方法
var myFun = function(){};//先声明一个对象
//用点语法添加方法
myFun.fun1 = function(){
}
myFun.fun2 = function(){
}
3.类
var myFun2 = function(){
this.getName = function(){
console.log('name');
}
this.getAge = function(){
console.log('age');
}
}
var fn = new myFun2(); //用new实例化对象
fn.getName();//用点语法使用函数
方法连用
var myFun2 = function(){
this.getName = function(){
console.log('name');
return this;
}
this.getAge = function(){
console.log('age');
return this;
}
}
var fn = new myFun2();
fn.getName().getAge();
每次new出的实例都会复制类的this上的方法 这样消耗大 可以将公共的方法添加到prototype上
var myFun3 = function(){};
myFun3.prototype = {
fun1:function(){
},
fun2:function(){
}
}
4.函数prototype原型上添加方法
//展示添加简单的方法
Function.prototype.addMethod = function(name,fn){
console.log('添加的方法');
}
//下面两种方式一样的实例化 methods methods1中都有原型中的方法addMethod
var methods = function(){};
var methods1 = new Function();
methods.addMethod();
methods1.addMethod();//都能打印出'添加的方法'
//添加多个方法 name:方法名 fn:方法函数
Function.prototype.addMethod = function(name,fn){
// this.name = fn;//点语法这里不能加方法 这里的this.name是获取属性
this[name] = fn;//用this[name]才是添加属性
}
var method2 = new Function();//实例化一个对象
//给他添加一个验证姓名的方法
method2.addMethod('checkName',function(){
console.log('我验证姓名');
})
method2.checkName();
// 链式添加方法 依旧用return this
Function.prototype.addMethod = function(name,fn){
this[name] = fn;
return this;
}
var method2 = new Function();//实例化一个对象
method2.addMethod('checkName',function(){
console.log('我验证姓名');
return this;//使用时可以链式使用函数
}).addMethod('checkEmail',function(){
console.log('我验证邮箱');
return this;
})
method2.checkName().checkEmail();//在函数内写return this 可链式使用
Function.prototype.addMethod = function(name,fn){
// this[name] = fn;
this.prototype[name] = fn;//这时添加在addMethod的原型上 后面使用方法需要new
return this;
}
var method2 = new Function();//实例化一个对象
method2.addMethod('checkName',function(){
console.log('我验证姓名');
return this;//使用时可以链式使用函数
}).addMethod('checkEmail',function(){
console.log('我验证邮箱');
return this;
})
var m = new method2();//需要new 因为方法在method的原型上 需要实例化
m.checkName().checkEmail();//在函数内写return this 可链式使用
5.创建对象的安全模式
有时创建对象(对象实例化)容易忘记new
如:
var Book = function(title,time,type){
this.title = title;
this.time = time;
this.type = type;
}
// 实例化一本书 却忘记了new 这时的book直接执行了Book,三个this的属性都添加给了window
var book = Book('书名','2014','js');
console.log(book);//undefined
console.log(window.title);//书名
console.log(window.time);//2014
console.log(window.type);//js
可以用安全模式:
var Book = function(title,time,type){
if (this instanceof Book) {//用instanceof判断this是否在Book的实例,不在则return重新new
this.title = title;
this.time = time;
this.type = type;
}else{
return new Book(title,time,type);
}
}
var book = Book('书名','2014','js');