海,
我试图理解 JavaScript 中的一些概念。考虑以下代码:
function Person(name, age)
{
this.name = name || "no name";
this.age = age || "age not specified";
this.printStr = function()
{
console.log("< " + this.name + ", " + this.age + " >");
};
}
p = new Person("pranav", 26);
p.printStr = function()
{
console.log("this works. also ...." + this.name);
};
p.printStr();
我想从“p”中“printStr”函数的实现中调用 Person 类中“printStr”的实现。
这样输出应该是:
< pranav, 26 >
this works. also ....pranav
有什么想法吗? :)
最佳答案
按照你现在的代码设置方式,你无法做到这一点。当您将 Person
作为构造函数调用时,最终成为 p
的对象将被设置为 this
。因此,当您在构造函数中定义 printStr
时,p
会获取一个名为 printStr
的属性。然后,当您分配第二个函数时,您可以覆盖它。
两个选项:一个非答案是做 pablochan 所做的事情 - 让内部的被称为 oldPrintStr
。另一种选择是使用原型(prototype)继承:
function Person(name, age)
{
this.name = name || "no name";
this.age = age || "age not specified";
}
Person.prototype.printStr = function() {
console.log("< " + this.name + ", " + this.age + " >");
};
然后你可以这样做:
p = new Person("pranav", 26);
p.printStr = function()
{
Person.prototype.printStr.apply(this);
console.log("this works. also ...." + this.name);
};
p.printStr();
关于javascript - 如何从替换的实现中调用类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1858815/