我正在一个名为 Animation.js 的文件中创建一个“类”:
function Animation(s) {
this.span = s;
};
Animation.prototype = Object.create(Animation.prototype);
Animation.prototype.constructor = Animation;
我创建了一个子类,它位于名为 LinearAnimation.js 的文件中:
function LinearAnimation(s, cP) {
Animation.call(s);
this.controlPoints = cP;
};
LinearAnimation.prototype = Object.create(Animation.prototype);
LinearAnimation.prototype.constructor = LinearAnimation;
问题是,当我访问 LinearAnimation 类中的 this.span
成员时,它说它是未定义
。我这个实现得好吗?谢谢。
最佳答案
Function.prototype.call()
函数采用 thisArg 作为第一个参数,即被调用函数内的 this
。之后,任何其他参数都会作为输入传递给被调用的函数。
此外,用从自身继承的对象替换函数(类)的原型(prototype)是没有意义的。
试试这个:
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);
关于Javascript继承,成员未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33553024/