2010-03-25 68 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) 

是一样的传球这在通过参数的全局变量中,但以优雅的形式。