0

How could I do this?

Class

var Factory = (function() {

  var Class = function() {

    this.name = 'John';

    this.methods = {
      get: function(callback) {
        callback();
      }
    };

  };

  return {
    createClass: function() {
      return new Class();
    }
  };

}());

Usage

var MyClass = Factory.createClass();

MyClass.methods.get(function() {
   this.name // => returns undenfined
});

Thanks for any help!

2
  • Actually, whats the meaning of your question here? And Post your exact Problem. Commented May 24, 2011 at 13:22
  • Oops, ‘How could I do this?’... Commented May 24, 2011 at 13:37

3 Answers 3

2

You need to save a reference to this in the outer Class function and call call:

var instance = this;

this.methods = {
  get: function(callback) {
    callback.call(instance);
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for quick reply! Is this the only one solution?
0
var Class = function() {
    // Save a reference to this that can be used in local closures.
    var me = this;

    this.name = 'John';

    this.methods = {
        get: function(callback) {
            // Use 'call()', passing the reference to the 'Class' object
            callback.call(me);
        }
    };
};

Comments

0

@SLaks - The declaration of scope as a Global variable is bad practice. @Ferdinand Beyer - have you tested if it functions?

The better way will be the scope binding. The Prototype javascript framework produced a nice concept and we can easily implement it like

Function.prototype.bind = function(scope) {
  var _function = this;

  return function() {
    return _function.apply(scope, arguments);
  }
}

and then yoou code should have only a single change and it will maintin the scope of your class.

var Factory = (function() {

  var Class = function() {

    this.name = 'John';
    var me = this;
    this.methods = {
      get: function(callback) {

        callback();
      }
    };

  };

  return {
    createClass: function() {
      return new Class();
    }
  };

}());

var MyClass = Factory.createClass();



MyClass.methods.get(function() {
   console.info(this.name) // => returns undenfined
}.bind(MyClass));

I mean only the function call get with .bind(MyClass)

2 Comments

My answer doesn't use any globals.
Ferdinand's answer is the same as mine, but with a different variable name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.