gpt4 book ai didi

javascript - 变量隐式声明和原型(prototype)

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:59 24 4
gpt4 key购买 nike

尽量保持简短。使用 phpstorm 查看我的代码并发现了一些错误。

它说我的函数命名位置有一个“隐式声明的变量”

function towngate10() {
updateDisplay(locations[10].description);
if (!gate10) {
score = score+5;
gate10 = true;
}
playerLocation = 10;
displayScore();
document.getElementById("goNorth").disabled=true;
document.getElementById("goSouth").disabled=false;
document.getElementById("goEast").disabled=true;
document.getElementById("goWest").disabled=true;
}

另外,我只是想确保我正确地制作了我的原型(prototype)只是一个例子

全局数组:

var locations = [10];
locations[0] = new Location(0,"Intersection","This is where you awoke.");
locations[1] = new Location(1,"Cornfield","The cornfields expand for miles.");
locations[2] = new Location(2,"Lake","A large lake that is formed by a river flowing from the East.", new Item(1,"Fish","An old rotting fish."));
locations[3] = new Location(3,"Outside Cave","Entrance to the dark cave.");

定位功能:

function Location(id, name, description, item) {
this.id = id;
this.name = name;
this.description = description;
this.item = item;
this.toString = function() {
return "Location: " + this.name + " - " + this.description;
}
}

最佳答案

关于隐式声明的变量:

if (!gate10) {
score = score+5;
gate10 = true;
}

playerLocation = 10;

score、gate 和 playerLocation 被创建为“全局”变量。 Phpstorm 会提醒你这一点。除非它们旨在全局访问,否则请使用 var 声明变量。这将使变量仅局限于创建它的范围:

if (!gate10) {
var score = score+5;
var gate10 = true;
}

var playerLocation = 10;

我建议您阅读更多关于 variable scoping 的内容.如果处理不当,全局变量可能会在您的安全中留下漏洞。

关于javascript - 变量隐式声明和原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29812938/

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