I am running two tests to check how objects worked in javascript:
Tests one:
//Method 1
var Player = {
name: "",
id: "",
action: {
action1: "",
action2: "",
action3: ""
}
}
var player1 = Object.create(Player);
player1.name = " hack";
player1.id = 1;
player1.action.action1 = "aaa";
player1.action.action2 = "aaa";
player1.action.action3 = "aaa";
console.log(JSON.stringify(player1.action));
var player2 = Object.create(Player);
player2.name = " Jason";
player2.id = 2;
player2.action.action1 = "bbb";
player2.action.action2 = "bbb";
player2.action.action3 = "bbb";
console.log(JSON.stringify(player2.action));
console.log(JSON.stringify(player1.action));
The result is:
{"action1":"aaa","action2":"aaa","action3":"aaa"}
VM174:29 {"action1":"bbb","action2":"bbb","action3":"bbb"}
VM174:30 {"action1":"bbb","action2":"bbb","action3":"bbb"}
you can see the action object of player1 had been changed by creating player2.
What if I want the action object preserve it's value?
The only way I can think about is following:
//Medthod 2
var actionManager = {
action1: "",
action2: "",
action3: ""
}
var Player = {
name: "",
id: "",
action: null
}
var player1 = Object.create(Player);
var actions1 = Object.create(actionManager);
actions1.action1 = "aaa";
actions1.action2 = "aaa";
actions1.action3 = "aaa";
player1.name = " hack";
player1.id = 1;
player1.action = actions1;
console.log(JSON.stringify(player1));
var player2 = Object.create(Player);
player2.name = " Jason";
player2.id = 2;
var actions2 = Object.create(actionManager);
actions2.action1 = "bbb";
actions2.action2 = "bbb";
actions2.action3 = "bbb";
player2.action = actions2;
console.log(JSON.stringify(player2));
console.log(JSON.stringify(player1));
In this case the output is:
{"name":"hack","id":1,"action:{"action1":"aaa","action2":"aaa","action3":"aaa"}}
{"name":" Jason","id":2,"action:{"action1":"bbb","action2":"bbb","action3":"bbb"}}
{"name":" hack","id":1,"action":{"action1":"aaa","action2":"aaa","action3":"aaa"}}
Is there any better way to use Method 1 but make the action object not being changed?