javascript – 从对象的内联函数中访问它

前端之家收集整理的这篇文章主要介绍了javascript – 从对象的内联函数中访问它前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在对象方法中,我无法从 JavaScript内联函数中引用“this”.
  1. var testObject = {
  2. oThis : this,testVariable : "somestring",init : function(){
  3.  
  4. console.log(this.testVariable); // outputs testVariable as expected
  5.  
  6. this.testObject.submit(function(){
  7.  
  8. var anotherThis = this;
  9. console.log(this.testVariable) // undefined
  10. console.log(oThis.testVariable) // undefined
  11. console.log(testObject.testVariable) // outputs testVariable
  12. console.log(anotherThis.testVariable) // undefined
  13.  
  14. }
  15.  
  16. }

如何从提交函数中访问this.testVariable?
我也使用jQuery,如果这有所作为.

我不知道这是否是最好的方法 – 也许我应该作为一个单独的函数提交,然后引用内联,像:

  1. init : function(){
  2.  
  3. this.testObject.submit = this.submitForm;
  4.  
  5. },submitForm : function(){
  6. // do validation here
  7. console.log(this.testVariable) // outputs testvariable
  8.  
  9. .
  10. .
  11. .
  12.  
  13. return valid;
  14. }

但是这似乎还没有起作用 – 而且我想我现在只想保持我的init方法里的submit函数.

解决方法

一个常见的方法是将您想要的这个分配给一个局部变量.
  1. init: function() {
  2. var _this = this;
  3. this.testObject.submit(function() {
  4. console.log(_this.testVariable); // outputs testVariable
  5. });
  6. }

猜你在找的JavaScript相关文章