Ember.js 是如何重新打开类工作的? [英] Ember.js how does reopenClass work?
问题描述
我不是很懂ember.js的reopenClass的功能.我认为它向对象的原型添加了额外的代码,因此该对象的所有实例都将获得以非静态方式添加的功能.然而,它不这样做.看起来它只添加了可以静态执行的代码.例如.我有这个代码:
I don't really get the function of ember.js' reopenClass. I thought it added extra code to the Object's prototype, so all instances of that Object would get the functionality that was added in a non static way. It does not do this however. It looks like it only adds code that can be statically executed. For instance. I have this code:
Logger = Ember.Object.extend({
log: function(thing) {
console.log(thing + ' wassup');
}
});
var logger = Logger.create();
logger.log("1, yo")
logger.reopen({
log: function(name) {
console.log(name + 'ghurt')
}
});
logger.log("2, yo")
Logger.reopenClass({
log: function(name) {
console.log(name + 'fresh')
}
});
logger.log("3, yo")
Logger.log("4, yo")
它输出这个:
1, yo wassup
2, yoghurt
3, yoghurt
4, yofresh
我的预期是这样的:
1, yo wassup
2, yoghurt
3, yofresh
4, undefined (I think)
所以我的问题是:reopenClass 有什么作用,我什么时候使用它?
So my question is: What does reopenClass do and when do I use it?
推荐答案
一般来说,reopen
添加方法和属性到 instances 而 reopenClass
向类添加方法和属性.
In general, reopen
adds methods and properties to instances whereas reopenClass
adds methods and properties to classes.
对应的测试是ember-runtime/tests/system/object/reopen_test.js 和 packages/ember-runtime/tests/system/object/reopenClass_test.js.
我已经更新了您的代码并添加了一些注释,请参阅 http://jsfiddle.net/pangratz666/yWKBF/:
I've updated your code and added some comments, see http://jsfiddle.net/pangratz666/yWKBF/:
Logger = Ember.Object.extend({
log: function(thing) {
console.log(thing + ' wassup');
}
});
var logger1 = Logger.create();
var logger2 = Logger.create();
// instances of Logger have a 'wassup' method
try { Logger.log("1, yo"); } catch (e) {} // Object (subclass of Ember.Object) has no method 'log'
logger1.log("1, yo"); // 1, yo wassup
logger2.log("1, yo"); // 1, yo wassup
console.log('----');
// overwrite log of concrete logger instance logger1
logger1.reopen({
log: function(name) {
console.log(name + ' ghurt');
}
});
try { Logger.log("1, yo"); } catch (e) {} // Object (subclass of Ember.Object) has no method 'log'
logger1.log("2, yo"); // 2, yo ghurt
logger2.log("2, yo"); // 2, yo wassup
console.log('----');
// classes of Logger have a 'fresh' method
Logger.reopenClass({
log: function(name) {
console.log(name + ' fresh');
}
});
Logger.log("3, yo"); // 3, yo fresh
logger1.log("3, yo"); // 3, yo ghurt
logger2.log("3, yo"); // 3, yo wassup
console.log('----');
// new* instances of Logger have from now on a 'dawg' method
// * this will likely change in the future so already existing instances will reopened too
Logger.reopen({
log: function(name) {
console.log(name + ' dawg');
}
});
Logger.log("4, yo"); // 4, yo fresh
logger1.log("4, yo"); // 4, yo ghurt
logger2.log("4, yo"); // 4, yo wassup
Logger.create().log("4, yo"); // 4, yo dawg
console.log('----');
这篇关于Ember.js 是如何重新打开类工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!