我对JavaScript中原型的概念很陌生。这让我很困惑,因为似乎有很多方法可以实现原型"继承"。来自Java背景,我的代码的结构大多类似于经典的OOP,因为这是我可以轻松理解它的方式。
我想调用原型中定义的函数,但我得到了Uncaught ReferenceError: getShape is not defined
。我甚至不确定我做这个原型的事情是否正确。
以下是我的代码片段:
function mouseOverAnimation($main,svgId) {
this.svg = getShape(svgId,$main); // this line works
function getShape(shapeId,parent) {
if (parent == undefined) { parent = svg; }
var shape = parent.find(shapeId);
return shape;
}
}
function someAnimationTest($main) {
this.prototype = new mouseOverAnimation($main,'#icon1');
this.ball1 = getShape('#ball1'); // this line is giving me the error
}
new someAnimationTest($('body'));
简单地解释一下我想做什么:我有多个svg图标,每个图标都需要鼠标悬停的动画。由于动画的代码基本相同,除了特定的动作,我认为使用原型是个好主意。我需要为每个图标做的第一件事是为我需要独立移动的每个形状获得vars。这就是我尝试使用getShape()
函数所做的。
getShape()
函数实际上是通过调用this.prototype = new mouseOverAnimation()
继承的吗?我该怎么称呼它?
附带一些可能与主要问题无关的次要问题:
我对更复杂的JavaScript还相当陌生。因此,我不确定我对this
、prototype
的使用以及我试图实现函数"重载"的方式。请随时纠正我的任何不好的地方。此外,在这个片段中使用了jQuery,因为它包含在我用于动画的库中,并且在我使用的一个示例中是这样使用的。不过,就这个例子而言,我认为实在不需要。为了简单起见,仍然使用这个$('body')
可以吗?还是将其改为普通JS更好?
我想调用原型中定义的函数,但我得到了未捕获的ReferenceError:getShape未定义。
由于someAnimationTest
方法的作用域中没有getShape
方法,因此会出现此错误。
getShape()函数是否通过调用this.prototype=新建mouseOverAnimation()?
getShape
方法未被继承,因为它不是mouseOverAnimation
原型的属性。
我应该怎么称呼它?
您需要将getShape
方法公开为mouseOverAnimation
的属性
function mouseOverAnimation($main,svgId) {
this.getShape = function (shapeId,parent) {
if (parent == undefined) { parent = svg; }
var shape = parent.find(shapeId);
return shape;
}
this.svg = this.getShape(svgId,$main); // this line works
}
并将其调用为
function someAnimationTest($main) {
this.moaInstance = new mouseOverAnimation($main,'#icon1'); //not using this.prototype as this has nothing to do with prototypical inheritence
this.ball1 = this.moaInstance.getShape('#ball1'); //notice that method is invoked via the instance of mouseOverAnimation 'this.moaInstance'
}