JSFiddle - React, Tailwind, and code Playground
by rhodee
JavaScript
//Method Invocation Pattern
//create an object literal
var myObject = {
points: 2,
//important! when a funciton is created as a property AND
// has access to this has ability to retrireve or modify
score: function (inc) {
// a funtion for scoring stuff
this.points += inc;
}
};
//run the score method directly on the object
myObject.score(10);
//direct access to the state property too
//alert(myObject.points);
//Function Invocation Pattern
//You have an existing object and want to add methods to it
//outside of its creation.
myObject.subtract = function () {
//to access the context of the object you need
//a workaround (below).
var that = this;
//now create a helper method you call
//within the scope of the new function on Object
var helper = function () {
that.points = that.points - 1
};
helper();
};
//Now call your method on the object directly
myObject.subtract();
alert(myObject.points);