我正在处理以下javascript文件
var utility = (function () {
var i = 1;
return {
nameGen: function () {
var name = "Number Of Candidate:" + i;
i = i + 1;
return name;
}
}
} ());
var name1 = utility.nameGen();
var name2 = utility.nameGen();
var name3 = utility.nameGen();
我正在调用我的html上面的javascript代码,但它无效?
答案 0 :(得分:2)
我在这里运行它(使用Firefox 29和Chrome 34.0.1847.131以及Internet Explorer 9),并添加console.log()
次调用以输出结果 -
var utility = (function () {
var i = 1;
return {
nameGen: function () {
var name = "Number Of Candidate:" + i;
i = i + 1;
return name;
}
}
} ());
var name1 = utility.nameGen();
var name2 = utility.nameGen();
var name3 = utility.nameGen();
console.log(name1);
console.log(name2);
console.log(name3);
我得到了输出
Number Of Candidate:1
Number Of Candidate:2
Number Of Candidate:3
答案 1 :(得分:0)
关闭此功能:
}) ();
答案 2 :(得分:0)
如果您想编写OOP JS,您应该执行以下操作:
function Utility() {
this.candidates = 1;
this.nameGen = function () {
var name = 'number of candidates' + this.candidates;
this.candidates++;
return name;
}
}
var utility = new Utility();
utility.nameGen(); // outputs "number of candidates1"
utility.nameGen(); // outputs "number of candidates2"
utility.nameGen(); // outputs "number of candidates3"
您可以阅读有关OOP JS here的更多信息。