I am trying to call the function MyMethod from within a object but none of the syntax below works. There must be a really obvious error below but I can't see it.
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/jscript"> function MyObject() { //how do I get one of these to work?? this.MyMethod; //does not work this.MyMethod(); //does not work either MyMethod(); //does not work either this.MyMethod = function () { alert('It works'); } } var test = new MyObject(); </script> </head> <body> </body> </html>
To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self.
The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
Calling a function from within itself is called recursion and the simple answer is, yes.
You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values. Copied!
There are two main problems
text/javascript
, not text/jscript
So:
function MyObject() { this.MyMethod = function () { alert('It works'); } this.MyMethod(); //should now work } var test = new MyObject();
First, setting it a property of the parent function, as is done in the "A" version of your script below. If you do this, the function is only usable after you give the definition.
Second, defining the function with the classical approach of "function functionName () { ... }". This definition undergoes "hoisting", which means the function becomes available throughout the parent object, i.e. even above the place it is defined. You can see this in the "B" version in the sample below, based on the original poster's code. Also on https://jsfiddle.net/dnL4j30u/
<script> function MyObject() { MyMethod(); this.MyMethod = function() { console.log('It works A'); } this.MyMethod(); MyMethod(); function MyMethod() { console.log('It works B'); } } var test = new MyObject(); </script>
The output is
It works B (this works because the second definition gets hoisted) It works A It works B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With