在对象内部创建指向函数的指针时,“ this”未正确解析
请尝试以下示例以获取概念...
// this.* fail
a = { x : 123, f : function(){ console.log( this.x ) } }
a.f() // 123
b = a.f // b points to a.f now
b() // should print 123 but gaves 'undefined'
您可以使用bind
:
b = a.f.bind(a);
b(); // 123
从MDN:
bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句