在某些大型項目中看到了這種JavaScript模式,它將ClassA的屬性「複製」或「實現」到ClassB,但無法弄清楚調用ClassA的空構造函數的目的是什麼在ClassB的構造函數中使用「.call()」而將ClassB實例作爲「this」綁定?JavaScript模式:將ClassA屬性「複製」到ClassB
var ClassA = function() {
//this function is totally empty
};
ClassA.prototype = {
jump: function() {...some code...},
dance: function() {
if (this.canDance) {
alert("dance");
}
}
};
ClassA.implementOn = function(targetClassOrObject) {
for (var prop in ClassA.prototype) {
targetClassOrObject[ prop ] = ClassA.prototype[ prop ];
}
};
var ClassB = function() {
this.canDance = true;
ClassA.call(this); // <------------What's the purpose of this line?
};
ClassA.implementOn(ClassB.prototype);
var instanceOfB = new ClassB();
instanceOfB.dance();
如果您刪除'ClassB',您會做些什麼? – Mathletics 2013-02-12 16:34:14
如果你的意思是刪除'ClassB'構造函數中的ClassA.call(this);'行,它似乎沒有任何區別。 – 2013-02-12 17:11:27
它只是因爲ClassA構造函數爲空而沒有任何區別。 – apsillers 2013-02-12 17:14:57