gpt4 book ai didi

javascript - 当对象存储在变量中时,而不是当对象存储在数组中时,对象的方法被调用

转载 作者:行者123 更新时间:2023-12-03 00:05:02 25 4
gpt4 key购买 nike

我使用构造函数方法在 Javascript 中定义了一个 Timeline 类,

function Timeline(formal parameters)
{
//property definitions
}

这些方法是在原型(prototype)对象上定义的,

Timeline.prototype.zoomMax = function(){ // Method Definition };

我使用数组来存储时间轴的对象,

var timeline = [];
timeline[0] = new Timeline(parameter's values);
timeline[1] = new Timeline(parameter's values);

但是当我调用 Timeline 的方法时,

timeline[0].zoomMax();

我收到错误,

Uncaught TypeError: Cannot read property 'zoomMax' of undefined

注意:我已经检查了打印时间线[0],对象正在存储在其中。

当我将对象存储在一个简单的变量而不是数组中时,它工作得很好,

var timeline = new Timeline(parameter's values);

timeline.zoomMax(); //Gives me the output

我不明白,如何对存储在数组中的对象调用 ZoomMax() 方法。

请指导。

我的时间线代码,

function Timeline(video_duration_in_sec,frames_per_sec = 25,zoom_value=1){

ComponentContainer.call(this,'time-cover');
this.video_duration_in_sec = video_duration_in_sec;
this.frame_count = video_duration_in_sec * frames_per_sec;
this.zoom_value = zoom_value;
this.ruler_width = this.video_duration_in_sec * (100/this.zoom_value);
this.min = 1;
this.max = 25;


}

最佳答案

使用class关键字定义对象类

class Timeline 
{
constructor(parameters) {
//property definitions, initialization...
}

zoomMax() {
console.log('zoom');
}
}


var timeline = [];
timeline[0] = new Timeline('parameters values');
timeline[1] = new Timeline('parameters values');

timeline[0].zoomMax();

关于javascript - 当对象存储在变量中时,而不是当对象存储在数组中时,对象的方法被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com