我无法理解下面的代码来自ember.js,并用于创建一个ember对象的实例:
var K = function() {};
Ember.create = function(obj, props) {
K.prototype = obj;
obj = new K();
if (props) {
K.prototype = obj;
for (var prop in props) {
K.prototype[prop] = props[prop].value;
}
obj = new K();
}
K.prototype = null;
return obj;
};
我不明白为什么K被设置为obj参数的原型,然后为什么再次调用new。
我不明白为什么这些行不止一次出现:
K.prototype = new K();
和
obj = new K()
有人可以解释为什么会这样吗?
答案 0 :(得分:0)
我认为在这个函数中有一个bug,因为这个函数用于IE8 - (source)而源Ember.create
对于所有其他浏览器的Object.create
是相等的。让我们试着解释一下:
var K = function() {};//base class (with empty constructor)
//inheritance function, create essence from obj with props
Ember.create = function(obj, props) {
K.prototype = obj;//classical inheritance from obj
obj = new K();//use obj instead of new var, create new essence
if (props) {//has methods
K.prototype = obj;//seams like a bug? Means obj from arguments, but get as new K()
for (var prop in props) {
K.prototype[prop] = props[prop].value;
}
obj = new K();//create essence with props (just create it again)
}
K.prototype = null;//reset methods, props
return obj;//return new essence
};
我认为作者的意思是这样的:
var stdClass = function() {};
Ember.create = function(proto, props) {
var createdEssence;
stdClass.prototype = proto;
if (props) {
for (var prop in props) {
stdClass.prototype[prop] = props[prop].value;
}
}
createdEssence = new stdClass();
stdClass.prototype = null;
return createdEssence;
};