Javascript继承,成员未定义

标签 javascript class constructor prototype prototypal-inheritance

我正在一个名为 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/

相关文章:

javascript - html 日期输入的最早日期是多少?

javascript - 从初始颜色计算调色板

javascript - 如何使用 javascript 获取当前 URL

c# - 如何在 C# 中的类中正确隐藏帮助程序(内部)类

java - 单击按钮后有什么方法可以向 build.prop 添加行?

vb.net - 如何在对象的构造函数完成后立即触发事件?

javascript - 谷歌地图信息窗口位置

ruby - 私有(private)方法 `select' 调用 nil :NilClass (NoMethodError)

java - 这个 UML 图中的包外观图标是什么意思?

c++ - 在 C++ 模板代码中找不到构造函数