简体   繁体   English

Javascript 基本实例化

[英]Javascript basic instanciation

I am a javascript newbie who's trying to transition from processing to javascript.我是一个 javascript 新手,正在尝试从处理过渡到 javascript。

Using Paper.js, I am simply trying to understand the equivalent of classes and their functions with the code below but keep having this error : Cannot read property 'move' of undefine.使用 Paper.js,我只是想通过下面的代码来理解类及其函数的等价物,但一直出现此错误:无法读取未定义的属性“移动”。

    function Apple (center) {
        this.color = 'red';
        this.center = center;
        this.path = new Path.Circle(this.center, 50);
        this.path.fillColor = 'black';
        return this.path;
    }

    Apple.prototype.move = function(){
        console.log('allo');
    }

var Apples = [];
var nbA = 10;

for(var i=0; i < nbA; i++){
    var center = new Point.random() * view.size;    
    Apples.push(new Apple(center));
}

function onFrame(event){
    for(var i=0; i < Apples.length; i++){
        Apples[i].prototype.move();
        }
    }

Can anybody shed some light ?有人可以解释一下吗? Thanks !谢谢 !

Change this:改变这个:

function onFrame(event){
    for(var i=0; i < Apples.length; i++){
        Apples[i].prototype.move();
        }
    }

to this:对此:

function onFrame(event){
    for(var i=0; i < Apples.length; i++){
        Apples[i].move();
        }
    }

the special prototype property adds properties (in this case a property that's a function) to all future instances of the specified class (in your case the Apple class).特殊的prototype属性将属性(在本例中为函数的属性)添加到指定类(在您的情况下为 Apple 类)的所有未来实例。

Also, to incorporate what Felix has said change this:此外,为了合并 Felix 所说的内容,请更改以下内容:

function Apple (center) {
        this.color = 'red';
        this.center = center;
        this.path = new Path.Circle(this.center, 50);
        this.path.fillColor = 'black';
        return this.path;
    }

to this:对此:

function Apple (center) {
        this.color = 'red';
        this.center = center;
        this.path = new Path.Circle(this.center, 50);
        this.path.fillColor = 'black';
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM