Advertisement
Guest User

Untitled

a guest
May 5th, 2016
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. var testObject = {
  2. oThis : this,
  3. testVariable : "somestring",
  4. init : function(){
  5.  
  6. console.log(this.testVariable); // outputs testVariable as expected
  7.  
  8. this.testObject.submit(function(){
  9.  
  10. var anotherThis = this;
  11. console.log(this.testVariable) // undefined
  12. console.log(oThis.testVariable) // undefined
  13. console.log(testObject.testVariable) // outputs testVariable
  14. console.log(anotherThis.testVariable) // undefined
  15.  
  16. }
  17.  
  18. }
  19.  
  20. init : function(){
  21.  
  22. this.testObject.submit = this.submitForm;
  23.  
  24. },
  25. submitForm : function(){
  26. // do validation here
  27. console.log(this.testVariable) // outputs testvariable
  28.  
  29. .
  30. .
  31. .
  32.  
  33. return valid;
  34. }
  35.  
  36. init: function() {
  37. var _this = this;
  38. this.testObject.submit(function() {
  39. console.log(_this.testVariable); // outputs testVariable
  40. });
  41. }
  42.  
  43. init: function() {
  44. // whatever
  45. var instance = this;
  46. instance.submitForm = function() {
  47. console.log(instance.testVariable);
  48. // ...
  49. };
  50. }
  51.  
  52. var testInstance = new testObject();
  53.  
  54. testInstance.oThis;
  55.  
  56. init: function(){
  57.  
  58. var self = this; // this allows you to access the parent object from different contexts
  59.  
  60. this.testObject.submit(function(){
  61.  
  62. console.log(self.testVariable);
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement