views:

102

answers:

2

How would I achieve something along the lines of this..

var Persistence = new Lawnchair('name');

Object.extend(Lawnchair.prototype, {
  UserDefaults: {
    setup: function(callback) {
                  // "save" is a native Lawnchair function that doesnt
                  //work because
                  // "this" does not reference "Lawnchair"
                  // but if I am one level up it does. Say if I defined
                  // a function called UserDefaults_setup() it would work
                  // but UserDefaults.setup does not work.
                  this.save({key: 'key', value: 'value'});


                // What is this functions scope?
                // How do I access Lawnchairs "this"
        }
    },

    Schedule: {
        refresh: function(callback) {

        }
    }
});

//this get called but doesnt work.
Persistence.UserDefaults.setup(); 
+1  A: 

UserDefaults is it's own object, so "this" refers to UserDefaults there. In other languages the result would be the same...accessing "this" within a function in an object that's a property of another object won't give you the parent.

The simplest solution is to use a version of dependency injection and just pass "this" in to the lower-level class:

var Persistence = new Lawnchair('name');

Object.extend(Lawnchair.prototype, {
  initialize: function(){
    // since initialize is the constructor when using prototype, 
    // this will always run
    this.UserDefaults.setParent(this);
  },
  UserDefaults: {
    setParent: function(parent){
        this.parent = parent;
    },
    setup: function(callback) {
                  // "save" is a native Lawnchair function that doesnt
                  //work because
                  // "this" does not reference "Lawnchair"
                  // but if I am one level up it does. Say if I defined
                  // a function called UserDefaults_setup() it would work
                  // but UserDefaults.setup does not work.
                  this.parent.save({key: 'key', value: 'value'});


                // What is this functions scope?
                // How do I access Lawnchairs "this"
        }
    },

    Schedule: {
        refresh: function(callback) {

        }
    }
});

//this get called but doesnt work.
Persistence.UserDefaults.setup(); 
jvenema
A: 

use bind(this)

setup: function(callback) { // "save" is a native Lawnchair function that doesnt //work because // "this" does not reference "Lawnchair" // but if I am one level up it does. Say if I defined // a function called UserDefaults_setup() it would work // but UserDefaults.setup does not work. this.save({key: 'key', value: 'value'});

        // What is this functions scope?
        // How do I access Lawnchairs "this"
}.bind(this) 

is the same of passing this in a global variable of by parameter but in an elegant form.

nahum silva