[英]Javascript inheritance, member undefined
I'm making a "class" in a file called Animation.js: 我在名为Animation.js的文件中创建“类”:
function Animation(s) {
this.span = s;
};
Animation.prototype = Object.create(Animation.prototype);
Animation.prototype.constructor = Animation;
And I create a child class which is in a file called LinearAnimation.js: 然后在名为LinearAnimation.js的文件中创建一个子类:
function LinearAnimation(s, cP) {
Animation.call(s);
this.controlPoints = cP;
};
LinearAnimation.prototype = Object.create(Animation.prototype);
LinearAnimation.prototype.constructor = LinearAnimation;
The problem is, when I access to this.span
member in the LinearAnimation class it says it's undefined
. 问题是,当我访问
this.span
成员在LinearAnimation类,它说这是undefined
。 Am I implementing this well? 我执行得很好吗? Thank you.
谢谢。
The Function.prototype.call()
function takes a thisArg as it's first argument, meant to be the this
inside the called function. Function.prototype.call()
函数将thisArg作为其第一个参数,这就是被调用函数内部的this
。 After that, any other argument(s) is(are..) passed as input to the called function. 之后,将任何其他参数作为输入传递给被调用的函数。
Also, there's no point in replacing the prototype of a function (class) with an object inherited from itself. 另外,用从自身继承的对象替换函数(类)的原型也没有意义。
Try this: 尝试这个:
function Animation(s) { this.span = s; }; function LinearAnimation(s, cP) { Animation.call(this, s); this.controlPoints = cP; }; LinearAnimation.prototype = Object.create(Animation.prototype); LinearAnimation.prototype.constructor = LinearAnimation; var la = new LinearAnimation('something', [1, 2, 3]); console.log(la);
You want Animation.call(this, s)
, not Animation.call(s)
. 您需要
Animation.call(this, s)
,而不是Animation.call(s)
。 The first argument to call
sets this
for the function invocation. call
的第一个参数this
函数调用设置this
参数。 In your code, you're calling Animation
with a this
of s
, so your s
argument gets a span
property, rather than the this
being constructed in LinearAniamtion
. 在代码中,你调用
Animation
与this
的s
,这样你的s
的说法得到了span
属性,而不是this
在正在兴建LinearAniamtion
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.