gpt4 book ai didi

javascript - 类型错误 : Cannot find function testFunction in object

转载 作者:行者123 更新时间:2023-12-03 12:11:17 27 4
gpt4 key购买 nike

我已经编写了一个位于我的对象内部的测试函数,但似乎无法访问该函数。我究竟做错了什么?我的意思是我确信我编写的代码很糟糕,但具体是什么导致了错误?:

function player(){

this.green=0;

function testFunction(){
this.green=99;
};
};

玩家对象在游戏对象中创建:

function game(numPlayers){

this.playerArray=[];

switch(numPlayers){
case 2:
this.player1=new player();
this.player2=new player();
this.playerArray.push(this.player1,this.player2);
break;
case 3:
this.player1=new player();
this.player2=new player();
this.player3=new player();
this.playerArray.push(this.player1,this.player2,this.player3);
break;
case 4:
this.player1=new player();
this.player2=new player();
this.player3=new player();
this.player4=new player();
this.playerArray.push(this.player1,this.player2,this.player3,this.player4);
break;
};

};

当我运行时:

var TE=new game(2);
TE.player1.testFunction(); <---
Logger.log(TE.player1.green);

我在主题行中收到错误。

最佳答案

您需要将 testFunction 定义为玩家对象的成员:

function player(){

this.green=0;

this.testFunction = function(){
this.green=99;
};
};

注意“this.testFunction = function() ...”

关于javascript - 类型错误 : Cannot find function testFunction in object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24952823/

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