因此在下面的代码中,我想知道this
关键字在这里如何工作? i
和this
从createstoken函数去哪里?
它是否转到令牌类中的this.id
?如果可以,为什么?
class Player{
constructor(playerNumber, tokenCount, tokenColor, active = false){
this.playerNumber = playerNumber
this.tokenCount = tokenCount
this.tokenColor = tokenColor
this.active = active
this.tokens = [createTokens(21)]
}
//creates tokens
createTokens(num){
let array = []
for(let i=0; i<num; i+=1){
const token = new Token(i, this)
array.push(token)
}
return array = []
}
}//end player
class Token{
constructor(){
this.owner = owner;
this.id = `token-${index}-${owner.id}`;
this.dropped = false;
}
}//end token
谢谢您的帮助!
答案 0 :(得分:0)
在您的代码中,this
表示在创建类的实例时正在构造的新对象:
class Player {
constructor(playerNumber) {
this.playerNumber = playerNumber;
//This refers to whatever object is being created - in the below instance, `this` would refer to `newPlayer`
}
}
const newPlayer = new Player(25);
答案 1 :(得分:0)
被调用的当前对象将被当作this.checkout这个简单的例子,因为我已经使用“ this”变量构造了一个对象。
“ new”关键字可以在构造函数中用于引用唯一对象。
查看示例:
function Maker(name,age){
//current object will be taken as this.
this.name=name;
this.age=age;
return this;
}
let firstObject = new Maker('bathri',22);
let secondObject = new Maker('bathri',22);
let result = [firstObject,secondObject];
console.log("first object",firstObject);
console.log("second object",secondObject);
console.log("result",result);