一、js方法 - 拒绝污染全局变量
建立function,应放入对象中
作用:防止污染全局变量
//method one
var A = {
search: function (){},
along: function (){},
feature: function (){}
}
//method two
var aFun = function (){
search = function (){};
along = function (){};
feature =function(){};
}
//how to use
A.search();
aFun.search();
问题:
Ⅰ、每次使用方法,会调用一次对象(复杂)
Ⅱ、单一使用,无法复制(复用)
二、js方法 - 链式调用
决解上一个问题Ⅰ
this 在方法中,指:当前对象
var A = {
search: function (){
//...
return this;
},
replace: function (){
//...
return this;
},
feature: function (){
//...
return this;
}
}
//var aFun = function (){} 同理
//how to use
A.search().replace().feature()
三、js方法 - 复用
决解上一个问题Ⅱ
1
// using the return
var aFun = function (){
return {
search = function (){};
along = function (){};
feature =function(){};
}
}
//how to use
var aInstance1 = aFun();
aInstance1.search();
var aInstance2 = aFun();
aInstance2.search();
2
//use the this whit the return
var aFun = function (){
this.search = function (){};
this.along = function (){};
this.feature =function(){};
return this;
}
//how to use
var aInstance1 = aFun();
aInstance1.search();
var aInstance2 = aFun();
aInstance2.search();```
## 3 ##
//use the prototype.js
var aFun = function (){
this.prototype.search = function (){};
this.prototype.along = function (){};
this.prototype.feature =function(){};
//return this; //or
}
//how to use
var aInstance1 = aFun();
aInstance1.search();
var aInstance2 = aFun();
aInstance2.search();
## 三、拓展 - js的基本类型『Function』
> 用于扩展“祖先”方法
> 使用prototype.js
> 『prototype.js 扩充了js基本对象:Function、Object、Array』
##1 - 使用Function 扩展##
//
Function.prototype.addMethod = function (name,fn){
this[name] = fn;
}
//how to use
var aInstance = new Function (){}
aInstance.addMethod(search,function (){});
aInstance.search();
##2 - 使用Function 链式扩展##
//
Function.prototype.addMethod = function (name,fn){
this[name] = fn;
return this;
}
//how to use
var aInstance = new Function (){}
aInstance.addMethod(‘search’,function (){}).addMethod(‘along’,function (){});
//
aInstance.search();
aInstance.along();
##3 - 将 实例 链式使用##
//
Function.prototype.addMethod = function (name,fn){
this[name] = fn;
return this;
}
//how to use
var aInstance = new Function (){}
aInstance.addMethod(‘search’,function (){
return this;
}).addMethod(‘along’,function (){
return this;
});
//
aInstance.search().along();
##4 - 函数式使用方法 ##
> 在满足以上三个问题(要求)的前提下,如何函数式调用你添加的方法?
Function.prototype.addMethod = function (name,fn){
this.prototype[name] = fn;
return this;
}
var ParentClass = new Function ();//等价 function()
ParentClass.addMethod(‘childrenMethod’,function (){
//…
return this;
})
var child = new ParentClass();
“`