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.
var MyObject = function MyObject() {
this.MyMethod = function () {
alert('It works');
} }
var test = new MyObject(); test.MyMethod();
The above will do. Or you can just create a constructor and call this method inside that. So at the time of object creation it will call this.MyMethod()
you have put the call to the private method inside the constructor of the javascript class. in that point the functions are not yet initialized
but if you initialize the object like so:
var test = new MyObject();
and then do this:
test.myMethod();
it will work.
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();
I'm pretty sure you can define methods anywhere in the file, even after you call them, but they way you are defining the method is the flaw.
http://ejohn.org/apps/learn/#5
Notice that if you define a variable with an anonymous function as it's value then you are not able to call the function by name (because it doesn't have one). Instead you should name it using the convention
function nameOfTheFunction( arguments ) {
...
}
I found the following link will to be very useful:
http://www.dustindiaz.com/javascript-function-declaration-ambiguity/
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