1

I am using Simple JavaScript Inheritance by John Resig. I know that I can use this variable to share values between methods:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  }
});

I would like to create a pointer to this so that it would not be overwriten later like:

$('#id').click(function() {
  // this now points to selector
});

How can I create let's say that = this pointer which would be accessible classwide?

untitled
  • 1,037
  • 2
  • 12
  • 27
  • 1
    Not sure what you mean or how that class would be used, but jQuery uses `bind` to set the right value of `this` inside callbacks ? – adeneo May 29 '14 at 13:19

3 Answers3

1

You can use '.apply()'

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },

  setDancing = function(isDancing) {
    this.dancing = isDancing;
  }
});

var p = new Person();

$('#id').click(function() {
  p.setDancing.call(p, NEWVALUE);
  // 'this' will point to 'p' in the function 'p.setDancing'
});
Dávid Szabó
  • 2,235
  • 2
  • 14
  • 26
  • The `click` event will be in the same class, not outside. I would like to define classwide variable and access it in all methods and even in `click` event in any of class methods. – untitled May 29 '14 at 13:35
0

The 'this' keyword always points to the environment it was instantiated in. For example:

function Obj(name)
{
this.name = name;
}

var me = new Obj('myName');
var you = new Obj('yourName');

me.name will return 'myName' and you.name will return 'yourName'.

You can only assign a pointer to it within the environment that it was created in, if it refers to nothing inside that environment, it points the global window. when you instantiate an object of init type, the 'this' pointer will point to isDancing.

Hawk
  • 788
  • 1
  • 6
  • 18
0

By adding this method, you can do the trick

addHandler: function() {
    var self = this;
    $('#id').click(function() {
      // self now points to this
    });
}
István
  • 5,057
  • 10
  • 38
  • 67
  • That's a good start but `self` will be accessible only in `addHandler` method. How to make it classwide without defining in each method? – untitled May 29 '14 at 13:25
  • 1
    I don't think there is a solution for this. – István May 29 '14 at 13:32
  • Does it mean that there is no new scope created to hold local variables in Simple JavaScript Inheritance? – untitled May 29 '14 at 14:42
  • What do you mean by local variables? In your case, class members? – István May 30 '14 at 05:23
  • That's how a closure works in JavaScript (http://stackoverflow.com/questions/111102/how-do-javascript-closures-work). – István May 30 '14 at 05:24
  • I was hoping that there is created scope in `var p = new Person();` so I could create variable and access it across Class methods. In fact I can do it with `this` variable but as I said before in some cases it gets overwritten. – untitled May 30 '14 at 10:34