So I’m trying my hand at JavaScript “classes” to try and clarify and simplify some of my code. What I have is something like this:
function action (name, vActor, vTarget) {
this.name = name;
this.vActor = vActor;
this.vTarget = vTarget;
this.addRoll = addRoll;
this.children = {};
}
function addRoll (name, diffMod, dice, success, critSuccess, failure) {
this.children[name] = {} ;
this.children[name].diffMod = diffMod;
this.children[name].dice = dice;
this.children[name].success = {condition: success, outcome: {}};
this.children[name].critSuccess = {condition: critSuccess, outcome: {}};
this.children[name].failure = {condition: failure, outcome: {}};
this.children[name].addSuccess = addSuccess;
this.children[name].addFailure = addFailure;
this.children[name].addOutcome = addOutcome;
}
Is this the right way to go about this? My main question is regarding who owns the “this” object in the “function addRoll()” section. I’m assuming that “this” still belongs to the action ‘class’. I also am uncertain of the syntax regarding starting a new blank object and assigning stuff using dot notation. Thanks in advance.
Ignoring function binding and calling apply or call, the
thisproperty is the owner of the method. Calling…The
thisproperty points to the globalwindowobject. If you had an object{}or instancenew Something()calledxwith the functionaddRoleand called it…The
thisproperty isx.Additional You have correctly assigned the function to the action object so when you call…
And then call
The
thisproperty is theainstance ofactionyou have created. To prevent it being called as a global function and adding properties to thewindowyou could assign it to aprototype. Theprototypeobject has some powerful features to build inheritance but for now simply changing…To the following…
And removing the assignment in action…
Will prevent the function accidentally being called without an owner
Further You could rewrite the way you assign the children in addRole to make greater use of object literal notation…
You could also refactor the code to use classes for the children as follows.