user1365697
user1365697

Reputation: 5989

Is this a closure in javascript?

I defined event 'on' to my object ( newobj )

In the event on I need access to this member that I saved it before.

The issue that I don't get this value in on event. ( doesn't exist )

I thought that I need to add closure I tried to add it but it didn't work.

Could you advise me what is the problem ?

Basic code

 create : function() {
    var self = this;
    var newObj = createNewObj()         
    newObj.on('selectData', function(evt){
                 ///some code on self
            }); 

With closure option 1

 create : function() {
    var self = this;
    var newObj = createNewObj() 
             return function(){     
    newObj.on('selectData', function(evt){

                 ///some code
            })}; 

With closure option 2

 create : function() {
    var self = this;
    var newObj = createNewObj() 
            newObj.on('selectData', function(evt){

            })
             return function(){
              // some code
}; 

Upvotes: 0

Views: 71

Answers (2)

Ramzi Khahil
Ramzi Khahil

Reputation: 5052

You can use the bind function. This simple changed the this inside the function.

Try something like this:

create : function() {
  var self = this;
  var newObj = createNewObj() 
  return (function(){     
    newObj.on('selectData', function(evt){
             ///some code
    }.bind(newObj)
  )})();
};

Sometime in the future you will be able to use a lexicaly bound function. See this article :)

Upvotes: 0

L0j1k
L0j1k

Reputation: 12635

Try this:

create : function() {
  var self = this;
  var newObj = createNewObj() 
  return (function(){     
    newObj.on('selectData', function(evt){
             ///some code
    }
  )})();
};

Upvotes: 1

Related Questions