How to provide a method call in the returned object literal use the assumed "this"

I have a javascript function that has a number of methods and variables and returns an object literal, which I use somewhat as a class, i.e.

var myObject = function {

   var somevars;
   var someMethod = function(someInput) { };

   return {
      methodA:function(inputs) { 
        // calls someMethod, using somevars and inputs 
      },
      methodB:function(inputs) { 
        // calls someMethod, using somevars and inputs 
      }

   };
}

In javascript, a variable is usually created called "this" or "I", or such a thing that stores the value of "this" at creation time, so that in future calls you can use it to point to your own objects because "this" may indicate something other. This is useful if, for example, methodA is used as a click handler.

How can I create the variable "this" in the returned object?

"" - , ?

, , , -.

, A methodB . "this".

"". X. X.methodA , . jquery, mouseup dom X.methodA. $( "# domElementId" ). Mousemove (X.methodA) mousemove, "this", A, X, . , . , A, , B, , this.methodB "this" .

+4
3

"" , , , :

var obj = {
    methodA: function() {
      // use obj here
    }
};
return obj;

, methodA .

, , . , , someMethod, somevars inputs, .

+6

new myObject(), :

  • JS .
  • JS myObject .
  • JS myObject , this .
  • new , 1, myObject ( ).

new this .

, , , this, . :

function myObject() {
    var somevars;

    this.methodA = function(inputs) { /* ... */ }.bind(this);
    this.methodB = function(inputs) { /* ... */ }.bind(this);
}

this , .

somevars, () ; , , , myObject, somevars.

( , , , , this , . , bind(), , , .)

0

bind()...

var myObject = function() {

   var somevars;
   var someMethod = function(someInput) { };
   this.foo = "bar";
   return {
      methodA:function(inputs) { 
        // calls someMethod, using somevars and inputs 
        //you can use the this.foo
      }.bind(this),
      methodB:function(inputs) { 
        // calls someMethod, using somevars and inputs 

      }.bind(this)

   };
}
-1

All Articles