像鸭子一样走路、游泳并且嘎嘎叫的鸟就是鸭子。
对javascript程序员来说,如果一个对象可以像鸭子一样走路、游泳并且嘎嘎叫,就认为这个对象是鸭子,哪怕它并不是从鸭子类的原型对象继承而来的。(摘自 权威指南215页)
<!--例一-->
<script>
var n=3;
Number.prototype.times=function(f){
var n=Number(this);
for(var i=0;i<n;i++) f.call(false,i); //调用function(n){ console.log(n+',hello')};
};
n.times(function(n){ console.log(n+',hello');});
</script>
<!--例二 去空格-->
<script>
//去空格trim()方法;
var s=' 2 2 22 2';
console.log(s);
console.log(s.trim());
// 自己模仿去空格
String.prototype.mytrim=function(){
if(!this) return this;
return this.replace(/^s+|s+$/g,'');
}
console.log(s.mytrim());
</script>
<!--例三 获取函数名-->
<script>
Function.prototype.getName=function(){
return this.name||this.toString().match(/functions*([^(]*)(/)[1];
};
alert(function ads(asd){ 'asd'}.getName());
</script>
集合类:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>
<script>
function Set(){
this.values={}; //几何数据保存在对象的属性里
this.n=0; //集合中值得个数
this.add.apply(this,arguments);
}
// 增
Set.prototype.add=function(){
for(var i=0;i<arguments.length;i++){
var val=arguments[i];
var str=Set._v2s(val);
if(!this.values.hasOwnProperty(str)){ //如果不存在
this.values[str]=val; //如果不在集合中就加入
this.n++;
}
}
return this;
}
// 删
Set.prototype.remove=function(){
for(var i=0;i<arguments.length;i++){
var str=set._v2s(arguments[i]);
if(this.values.hasownproperty(str)){
delete this.values[str];
this.n--;
}
}
return this;
}
//查 是否存在这个元素
Set.prototype.contains=function(value){
return this.values.hasOwnProperty(Set._v2s(value));
}
//查 个数
Set.prototype.size=function(){
return this.n;
}
//
Set.prototype.foreach=function(f,context){
for(var s in this.values)
if(this.values.hasOwnProperty(s))
f.call(context,this.values[s]);
};
//值与字符串对应起来
Set._v2s=function(val){
switch(val){
case undefined: return 'u';
case null: return 'n';
case true: return 't';
case false: return 'f';
default:switch(typeof val){
case 'number': return '#'+val;
case 'string': return '"'+val;
default: return '@'+object(val);
}
}
function objectId(o){
var prop="|**objectid**|";
if(!o.hasOwnProperty(prop))
o[prop]=Set._v2s.next++;
return o[prop];
}
};
Set._v2s.next=100; //初始化id的值100
</script>