我正在使用JavaScript中的類繼承方法之一(正如我正在修改的代碼中使用的那樣),但不理解如何將子類中的方法的附加功能附加到相應父類方法的功能已經有了;換句話說,我想用一個方法覆蓋子類中的父方法,除了它自己的子類特定的東西外,父方法也是這樣做的。所以,我試圖從孩子的方法調用父母的方法,但它甚至有可能嗎?如何從JavaScript中的子類調用父類的方法,以便可以訪問父類的局部變量?
代碼在這裏:http://jsfiddle.net/7zMnW/。請打開開發控制檯查看輸出。這裏還
代碼:
function MakeAsSubclass (parent, child)
{
child.prototype = new parent; // No constructor arguments possible at this point.
child.prototype.baseClass = parent.prototype.constructor;
child.prototype.constructor = child;
child.prototype.parent = child.prototype; // For the 2nd way of calling MethodB.
}
function Parent (inVar)
{
var parentVar = inVar;
this.MethodA = function() {console.log("Parent's MethodA sees parent's local variable:", parentVar);};
this.MethodB = function() {console.log("Parent's MethodB doesn't see parent's local variable:", parentVar);};
}
function Child (inVar)
{
Child.prototype.baseClass.apply(this, arguments);
this.MethodB = function()
{
console.log("Child's method start");
Child.prototype.MethodB.apply(this, arguments); // 1st way
this.parent.MethodB.apply(this, arguments); // 2 2nd way
console.log("Child's method end");
};
}
MakeAsSubclass(Parent, Child);
var child = new Child(7);
child.MethodA();
child.MethodB();
不,你不能看到父母的本地變量。你繼承了父母的原型鏈,而不是他們的本地狀態。 –