【问题标题】:Prototypes Object.extend with multiple objects that contain there own functions原型 Object.extend 包含多个对象,其中包含自己的功能
【发布时间】:2011-01-31 13:26:57
【问题描述】:
我将如何实现这一点..
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();
【问题讨论】:
标签:
javascript
prototype
javascript-intellisense
【解决方案1】:
使用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 相同,但形式优雅。
【解决方案2】:
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();