var Class = function(){ var klass = function(){ this.init.apply(this,arguments); }; klass.prototype.proxy = function(func){ var self = this; return (function(){ return func.apply(self,arguments); }); }; klass.prototype.include = function(obj){ for(var i in obj){ klass.prototype[i] = obj[i]; } }; return klass; }; var buton = new Class(); buton.include({ init:function(element){ this.element = jQuery(element); //保证上下文一致,保证click function的作用于是整个上下文 this.element.click(this.proxy(this.click)); }, click:function(){}, });
看这个一段使用代理的代码,里面的一片代码
klass.prototype.proxy = function(func){ var self = this; return (function(){ return func.apply(self,arguments); }); };
简单点描述就是proxy代理里面的func方法,它的作用域会放到外面一层的作用域,使上下文一致。
理解代理,我们可以看一下这段代码
var Car = function(){ this.CarName = "Mini"; }; Car.prototype.getName = function(){ document.getElementById(‘nameBtn‘).addEventListener(‘click‘,function(){ console.log(this.CarName); }) }; var car = new Car(); car.getName();//undefined
为什么会爆undefined呢?是因为在addEventListener里面this指针的作用域和Car里面的指针作用域不一样。addEventListener里面没有this.CarName
所以解决的方案是:
var Car = function(){ this.CarName = "Mini"; }; Car.prototype.getName = function(){ var self = this; document.getElementById(‘nameBtn‘).addEventListener(‘click‘,function(){ console.log(self.CarName); }) }; var car = new Car(); car.getName();//Mini
=======================================================================================
最后的版本:
var Car = function(){ this.CarName = "Mini"; }; Car.prototype.getName = function(){ document.getElementById(‘nameBtn‘).addEventListener(‘click‘,this.proxy(this.clickEvent)); }; Car.prototype.proxy = function(func){ var self = this; return (function(){ return func.apply(self,arguments); }); }; var car = new Car(); car.clickEvent = function(){ console.log(this.CarName); }; car.getName();//Mini
时间: 2024-12-22 17:44:42