0

これに沿ってどのように何かを達成するでしょうか。

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(); 
4

2 に答える 2

1

UserDefaultsはそれ自体のオブジェクトであるため、「this」はそこでのUserDefaultsを指します。他の言語では、結果は同じになります...別のオブジェクトのプロパティであるオブジェクトの関数内で「this」にアクセスしても、親は得られません。

最も簡単な解決策は、依存性注入のバージョンを使用して、「this」を下位レベルのクラスに渡すことです。

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(); 
于 2010-03-25T05:35:41.980 に答える
0

使用する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) 

これをbyパラメーターのグローバル変数で渡すのと同じですが、エレガントな形式で渡します。

于 2010-04-02T06:27:22.567 に答える