TypeError:string不是函数

时间:2012-12-29 12:33:38

标签: javascript string object instantiation typeerror

在以下代码中,第30行TypeError: string is not a function上会出现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);
};

2 个答案:

答案 0 :(得分: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);
};​

Demo

答案 1 :(得分:3)

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