我实现了继承链Vehicle -> Motorized -> Car
:
function Vehicle()
{
var m_name;
this.setName = function(pName) {
m_name = pName;
};
this.getName = function() {
return m_name;
};
}
function Motorized()
{
var m_started = false;
this.start = function() {
m_started = true;
console.log(getName() + " started");
};
}
function Car()
{ }
//set up the inheritance chain
Motorized.prototype = new Vehicle();
Car.prototype = new Motorized();
// use
var lCar = new Car;
lCar.setName("Focus");
console.log(lCar.getName()); // Focus
lCar.start(); // ReferenceError: getName is not defined
当我调用lCar.start()
(在函数Motorized中定义)时,我得到一个 ReferenceError:getName未定义。如何在子类getName()
中使用inherted方法Motorized
?
答案 0 :(得分:1)
因为Javascript不知道在哪里查找getName()
方法。您可以澄清声明始终指向正确对象的self
变量的语法,如下所示:
function Vehicle()
{
var self = this; // Vehicle
var m_name;
this.setName = function(pName) {
self.m_name = pName;
};
this.getName = function() {
return self.m_name;
};
}
function Motorized()
{
var self = this; // Motorized
var m_started = false;
this.start = function() {
/*
`self` is Motorized, with proto Vehicle, so
has a getName() method.
`this` instead is the object where you call
start() from, i.e. Car, in the example down below.
*/
self.m_started = true;
console.log(self.getName() + " started");
};
}
function Car()
{ }
//set up the inheritance chain
Motorized.prototype = new Vehicle();
Car.prototype = new Motorized();
// use
var lCar = new Car;
lCar.setName("Focus");
console.log(lCar.getName()); // Focus
lCar.start(); // Focus started
请注意,在这种情况下,在整个代码中使用关键字this
代替self
也会有效,但您绝对不能在getName()
之前省略它。此外,如果您计划稍后添加更多代码,例如jQuery中的事件处理程序,那么明确引用您编写的类可能很有用,因为this
可能变得很容易模糊,至少从人的观点。
无论如何,使用self
是否是一种糟糕的编码模式是this question的主题;您的示例中的要点是您需要致电self.getName()
或this.getName()
。