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) 

与通过参数的全局变量传递 this 相同,但以优雅的形式传递。

于 2010-04-02T06:27:22.567 回答