简体   繁体   中英

Dynamically call javascript object function from html

I'm working on a kind of javascript text-based game engine. I have a javascript object with an 'onuse' method. This works fantastically when I use it like this:

var button = new CanvasObject();
button.text = "test" // Necessary for the next code sample
button.onuse = function(){ button.x += 1 }; // Some simple reaction;

I have code in a Canvas object that when drawing a CanvasObject will wrap it in a span tag like so:

<span onclick = "function{ button.x += 1 }">test</span>
// Or to make the HTML cleaner:
<span onclick = canvas.callFunction(5)>test</span>
// where canvas.callFunction will call the function needed.
// Canvas keeps an array of functions that can be called.

The Canvas will call the function, and since it uses 'absolute' terms, the line 'button.x += 1', will work fine. The problem is that I have another class that I extended from CanvasObject, for example, ButtonObject. I want the class definition to have an onuse function that is already defined. For example (using the inheritance technique lined out here )

ButtonObject.method('onuse', function(){
   this.x++; // Some function requiring 'this'.
});

When I called a function from the HTML using the first technique, my engine would just call it as an anonymous function. Then, 'this' then would be defined as the window. I want every instance of ButtonObject to have the same 'onuse' function, so defining it each time like I did with CanvasObject seems like a lot of extra code. One possible solution I thought of was to modify the way my engine works such that each object is given a 'name' property, that is equivalent to it's javascript name. This way the engine could simple write the string like this:

innerHTML += ( "<span onclick=' + buttonObjectInstance.name + ".onuse()'>" );

But this technique would require me to state the name of the object twice, every time I instantiate it, like this:

var startButton = ButtonObject('startButton');

Is this truly my only option? Or is there way to call a function in the context of the object without having the name of that object?

bind a function to this for later:

ButtonObject.method('onuse', function(){
   this.x++; // Some function requiring 'this'.
} .bind(ButtonObject)  );

of if not ButtonObject in the calling context, bind it to whatever holds your methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM