//给函数的prototype新增名字为name,函数体为fn的函数 Function.prototype.method =function(name,fn){ this.prototype[name] = fn;//this return this; } //再扩展Array的方法,新方法的名字,函数体,形参,实参 if(!Array.prototype.forEach){ //Array.prototype.forEach = function(fn,thisObj){} //this.fns.forEach( function(el){el(o);} ) function(el){el(o)是函数实参 Array.method("forEach",function(fn,thisObj){//forRach是函数名字,后面是函数声明,fn,thisObj是声明里的形参 var scope = thisObj || window; for (var i = 0; i < this.length; i++) { fn.call(scope,this[i],i,this); } }) } if(!Array.prototype.filter){ //this.fns.filter(function(el){if(el != xxx){return el;}}) Array.method("filter",function(fn,thisObj){ var scope = thisObj || window; var a = []; for (var i = 0; i < array.length; i++) { if( !fn.call(scope,this[i],i,this) ){ continue; } a.push(this[i]) } //.......................... return a; }) }
window.DED = window.DED||{};//有就用自己,没有就用空对象 DED.util = DED.util || {} //观察者 DED.util.Observer = function(){ this.fns = [] } //扩展他 DED.util.Observer.prototype = { //观察 subscribe : function(fn){ this.fns.push(fn); }, //取消观察 unsubscribe : function(fn){ this.fns = this.fns.filter(function(el){ if(el != fn){ return el; } }) }, //循环执行函数被观察的数组 fire:function(o){ this.fns.forEach(function(el){ el(o); }) } }
addEvent(items, ‘click‘, function(e) { var e = e || window.event; var src = e.target || e.srcElement; try { e.preventDefault(); } catch (ex) { e.returnValue = false; }
function F(){} var f = function(){} Function.prototype.method =function(name,fn){ alert(1); } f.method();//1 F.method();//1 function F(){} var f = function(){} Function.prototype.method =function(name,fn){ this.prototype[name] = fn; return this; } f.method("a",function(){alert("a");});//1 F.method("b",function(){alert("b");});//1 //f.a();//f.a is not a function f.prototype.a();//a //F.b();//F.b is not a function F.prototype.b()//b new F().b();//b
形参看成构造函数传入的成员变量的值。函数名看成类名。this.看成成员属性和成员方法。
function addCar(){ this.name = 11; this.begin = function(){//对象的成员方法属性可以用中括号获取 alert(1); } } new addCar().begin();//1 alert(new addCar()["begin"]);//this.begin = function(){alert(1);} alert(typeof new addCar()["begin"]);//function new addCar()["begin"]();//1 alert(new addCar()["name"]);//11 var rr = new addCar(); rr["age"] = 444; alert(rr["age"]);//444 rr["fff"] = function(){alert(777);} rr["fff"]();//777
时间: 2024-12-29 23:22:36