2010-03-25 65 views
0

我將如何實現沿此線的東西多個對象..原型Object.extend與包含有自己的功能

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

UserDefaults是它自己的對象,所以「這」指的是UserDefaults那裏。在其他語言中,結果將是相同的...在另一個對象的屬性的對象中的函數中訪問「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(); 
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) 

是一樣的傳球這在通過參數的全局變量中,但以優雅的形式。