javascript 类型错误:字符串不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14081724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: string is not a function
提问by Nate
In the following code, TypeError: string is not a function
on line 30 var myColour = new colour(255,255,255);
is thrown. Can anyone see what is wrong with the code. Many thanks.
在下面的代码中,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);
};
回答by Some Guy
You have a local variable called colour
in the for...in
loop, and that is not a function. Change that variable to something other than the constructor function, like c
and it'll work fine. Your code, corrected:
你有一个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);
};?
回答by Hui Zheng
Local variable colour
defined in for (var colour in colours)
will be hoistedto the beginning of the onload
function, so it will hide the global function colour
. Changing the latter to Colour
will solve your problem. Besides, it's good convention to capitalize the name of a function which serves as a Class
name.
中colour
定义的局部变量for (var colour in colours)
会被提升到onload
函数的开头,所以会隐藏全局函数colour
。将后者更改为Colour
将解决您的问题。此外,将用作名称的函数的名称大写是一个很好的约定Class
。