this.lastData, theInstance.lastData and self.lastData

For developers using the Construct 2 Javascript SDK

Post » Wed Jan 13, 2016 8:04 pm

Studying the AJAX plugin as refence, i found "lastData" in 3 situations:

Code 1
Code: Select all
pluginProto.Instance = function(type)
   {   
       ...
      this.lastData = "";


Code 2
Code: Select all
var theInstance = null;

window["C2_AJAX_DCSide"] = function (event_, tag_, param_)
   {
         ...
         theInstance.lastData = param_;
   }

instanceProto.onCreate = function()
   {
      theInstance = this;
   };


Code 3
Code: Select all
var self = this;

var errorFunc = function ()
      {
    self.lastData = data.replace(/\r\n/g, "\n")


Code 4
Code: Select all
Exps.prototype.LastData = function (ret)
   {
      ret.set_string(this.lastData);
   };



The first 2 codes I think it´s talking about the "Instances" propertie (between the 3 Classes: Plugin, type and Intance).

Why in code 3 is using "self" ?

In code 4 the "this.lastData" refers to the instace too?
B
18
S
4
G
1
Posts: 143
Reputation: 1,868

Post » Wed Jan 13, 2016 8:46 pm

In 1 and 4 "this" is the current instance.

In 2 "this" in the onCreate function is the current instance. It's set to a global variable so the instance can be referenced in that widow callback.

In 3 self is used so the callback "errorFunc" can access the instance. Otherwise I think this would be the global window object.


The following link probably is better help:
http://javascriptissexy.com/understand- ... master-it/
B
94
S
33
G
118
Posts: 5,396
Reputation: 75,853

Post » Thu Jan 14, 2016 6:54 am

Thanks @R0J0hound, just perfect!

The problem was the nested function.
When "this" is inside a nested expression function (example called "A"), that is inside the "instanceProto" function, Calling the "A" function will get you the global object, in Strict mode, undefined (that was the trick part). That´s the reason for defining the "self"...you are right.
B
18
S
4
G
1
Posts: 143
Reputation: 1,868


Return to Javascript SDK

Who is online

Users browsing this forum: No registered users and 0 guests