在 JavaScript 中添加私有方法?
Add private method in JavaScript?
我正在尝试制作一款基础游戏来增强我的 JavaScript 知识。但是我需要一些帮助来尝试向对象添加私有方法。这样做的原因是我希望用户能够在达到特定条件后访问某些移动,但不能在此之前访问。我也不想每次角色升级时都必须添加方法。这是一些代码:
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
//Ignore this part as well this.punch = function() {
//Ignore this. Will work on later
}
};
var rock = new Character('Stoner', 'Rock', 'Male');
如果您使用 "var" 而不是 this.punch,它将变为私有。
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
var punch = function() {
//Ignore this. Will work on later
}
};
var rock = new Character('Stoner', 'Rock', 'Male');
这完全是猜测,但这是我根据看起来 的想法得出的意见。暂时想不出别的办法。
function Character(name, type, sex) {
var level = 1;
this.name = name;
this.type = type;
this.sex = sex;
this.punch = function() {
// If the user isn't over level 5, don't punch anything
if (level < 5) {
return;
}
// Punch something
}
}
显然你需要一些升级角色的方法...
I don't think this is what the OP is looking for... It seems like the OP wants them "private" until the user hits a certain level and then public
假设这个评论是正确的...
不需要是私有方法,可以是public方法,如果不够用if/else语句处理"levels" .
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
this.level = 10;
this.punch = (function(){
if (this.level > 5) {
/* Punch functionality goes here. */
} else {
/* They don't have enough levels, tell them that! */
}
}).bind(this)
}
我只是假设您使用的是关卡。如果你有其他系统,你可以简单地适应它。
我正在尝试制作一款基础游戏来增强我的 JavaScript 知识。但是我需要一些帮助来尝试向对象添加私有方法。这样做的原因是我希望用户能够在达到特定条件后访问某些移动,但不能在此之前访问。我也不想每次角色升级时都必须添加方法。这是一些代码:
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
//Ignore this part as well this.punch = function() {
//Ignore this. Will work on later
}
};
var rock = new Character('Stoner', 'Rock', 'Male');
如果您使用 "var" 而不是 this.punch,它将变为私有。
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
var punch = function() {
//Ignore this. Will work on later
}
};
var rock = new Character('Stoner', 'Rock', 'Male');
这完全是猜测,但这是我根据看起来 的想法得出的意见。暂时想不出别的办法。
function Character(name, type, sex) {
var level = 1;
this.name = name;
this.type = type;
this.sex = sex;
this.punch = function() {
// If the user isn't over level 5, don't punch anything
if (level < 5) {
return;
}
// Punch something
}
}
显然你需要一些升级角色的方法...
I don't think this is what the OP is looking for... It seems like the OP wants them "private" until the user hits a certain level and then public
假设这个评论是正确的...
不需要是私有方法,可以是public方法,如果不够用if/else语句处理"levels" .
function Character(name, type, sex) {
this.name = name;
this.type = type;
this.sex = sex;
this.level = 10;
this.punch = (function(){
if (this.level > 5) {
/* Punch functionality goes here. */
} else {
/* They don't have enough levels, tell them that! */
}
}).bind(this)
}
我只是假设您使用的是关卡。如果你有其他系统,你可以简单地适应它。