3 回答
TA贡献1951条经验 获得超3个赞
MyClass
var myThis=this;this.elements.each(function() { myThis.doSomething.apply(myThis, arguments); });
each
, this
doSomething
myThis
apply
arguments
this
myThis
doSomething
.
TA贡献1810条经验 获得超4个赞
var f=function(){ var context=this;} f.prototype.test=function(){ return context;} var fn=new f();fn.test(); // should return undefined because the prototype definition // took place outside the scope where 'context' is available
var f=function(){ var context=this; this.test=function(){ console.log(context); return context; };} var fn=new(f);fn.test(); //should return an object that correctly references 'this'//in the context of that function; fn.test().test().test(); //proving that 'this' is the correct reference;
var f=function(val){ var self=this; this.chain=function(){ return self; }; this.checkval=function(){ return val; };} var fn1=new f('first value');var fn2=new f('second value'); fn1.checkval();fn1.chain().chain().checkval(); // returns 'first value' indicating that not only does the initiated value remain untouched, // one can use the internally stored context reference rigorously without losing sight of local variables. fn2.checkval();fn2.chain().chain().checkval();// the fact that this set of tests returns 'second value' // proves that they are really referencing separate instances
fn=new function(val){ var self=this; this.chain=function(){ return self; }; this.checkval=function(){ return val; }; } fn.checkval();fn.chain().chain().checkval();
专业人士:
它使您的代码更易于阅读,因为它缩进函数对象的方法,使其直观地更易于理解。 它允许访问本地定义的变量。 仅在最初以这种方式定义的方法中
即使稍后向函数对象添加原型函数或成员函数,它也不能访问局部变量,而且您在该级别上存储的任何功能或数据在其他任何地方都是安全和不可访问的。 它允许一种简单而直截了当的方式来定义单子。 它允许您存储对“this”的引用,并无限期地维护该引用。
康:
添加回答
举报