原型Object.extend包含多个包含自己的函数的对象

时间:2010-03-25 03:41:43

标签: javascript prototype javascript-intellisense

我将如何实现这一点......

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

2 个答案:

答案 0 :(得分: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(); 

答案 1 :(得分: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) 

与在参数的全局变量中以优雅的形式传递它是一样的。

相关问题