Javascript 如何访问对象方法上的Ember对象范围
从概念上讲,我希望能够在能够访问对象的Javascript 如何访问对象方法上的Ember对象范围,javascript,ember.js,Javascript,Ember.js,从概念上讲,我希望能够在能够访问对象的this的Ember对象中定义方法,而不必将它们声明为计算属性或观察者。目前,可以这样做: var TestObj = Ember.Object.extend({ testFunc: function(self, arg1, arg2) { self.set("testProperty1", arg1); self.set("testProperty2", arg2); }, init: functio
this
的Ember对象中定义方法,而不必将它们声明为计算属性或观察者。目前,可以这样做:
var TestObj = Ember.Object.extend({
testFunc: function(self, arg1, arg2) {
self.set("testProperty1", arg1);
self.set("testProperty2", arg2);
},
init: function() {
this._super();
this.get("testFunc")(self, "test1", "test2");
}
});
在上面的示例中,我通过将对象的this
属性传递给参数self
中的函数,模拟了对该属性的访问。然而,这有点老套。是否有任何方法可以在对this
属性具有完全访问权限的Ember对象上创建方法,如下所示:
var TestObj = Ember.Object.extend({
testFunc: function(arg1, arg2) {
this.set("testProperty1", arg1);
this.set("testProperty2", arg2);
},
init: function() {
this._super();
this.get("testFunc")("test1", "test2");
}
});
我意识到这在Ember中可能不是惯用的,但我经常发现我希望能够编写在Ember对象中可多次重用的函数,这就需要能够创建方法。如果它不存在,也许这样的语法可以工作:
var TestObj = Ember.Object.extend({
testFunc: function(arg1, arg2) {
this.set("testProperty1", arg1);
this.set("testProperty2", arg2);
}.method(),
init: function() {
this._super();
this.call("testFunc", "test1", "test2");
}
});
对于
this.call
函数,第一个参数是应该调用的方法的名称,其余参数是要传递给该方法的参数。想法?您是否考虑过在javascript中使用“调用”或“绑定”。是的,但是这两种方法都不能真正解决必须手动指定函数this
的上下文的问题。我建议的语法将意味着此
自动绑定到testFunc
,而无需在对testFunc
的每个函数调用中指定。