3

在下面的代码中,TypeError: string is not a function第 30 行var myColour = new colour(255,255,255);被抛出。任何人都可以看到代码有什么问题。非常感谢。

var bodies = [];
var orbits = [];
var colours = [
    new colour(45, 45, 45),
    new colour(255, 0, 0),
    new colour(0, 157, 255),
    new colour(77, 250, 81),
    new colour(255, 247, 0)
];

function colour(red, green, blue)
{
    this.red = red;
    this.green = green;
    this.blue = blue;
};

window.onload = function() {
    var c = document.getElementById("theCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(95,50,40,0,2*Math.PI);
    ctx.stroke();
    for (var colour in colours){
        console.log(colour.red);
        console.log(colour.green);
        console.log(colour.blue);
    };
    var myColour = new colour(255,255,255);
    console.log(myColour.red);
    console.log(myColour.green);
    console.log(myColour.blue);
};
4

2 回答 2

7

colour您在循环中调用了一个局部变量for...in,这不是一个函数。将该变量更改为构造函数以外的其他内容,例如c它会正常工作。您的代码,更正:

var bodies = [];
var orbits = [];
var colours = [
    new colour(45, 45, 45),
    new colour(255, 0, 0),
    new colour(0, 157, 255),
    new colour(77, 250, 81),
    new colour(255, 247, 0)
];

function colour(red, green, blue)
{
    this.red = red;
    this.green = green;
    this.blue = blue;
};

window.onload = function() {
    var c = document.getElementById("theCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(95,50,40,0,2*Math.PI);
    ctx.stroke();
    for (var c in colours){
        console.log(c.red);
        console.log(c.green);
        console.log(c.blue);
    };
    var myColour = new colour(255,255,255);
    console.log(myColour.red);
    console.log(myColour.green);
    console.log(myColour.blue);
};​

演示

于 2012-12-29T12:36:21.510 回答
3

colour中定义的局部变量for (var colour in colours)将被提升onload函数的开头,因此它将隐藏全局函数colour。将后者更改为Colour将解决您的问题。此外,将用作名称的函数的名称大写是一个很好的约定Class

于 2012-12-29T12:44:43.960 回答