Reputation: 63567
I have a js object with two functions. What is the right way to call mySecondFunction()
from myFirstFunction()
? Should it be this.mySecondFunction()? Or MyObject.mySecondFunction()?
I thought I would use "this", but if it is inside of an Event handler, then "this" refers to the DOM element and not to the object :(
var MyObject = {
firstFunction: function() {
whatgoeshere???.mySecondFunction();
},
secondFunction: function() {
console.log('Hi!');
}
}
Upvotes: 0
Views: 147
Reputation: 23622
var MyObject = {
firstFunction: function() {
this.mySecondFunction();
},
secondFunction: function() {
console.log('Hi!');
},
mySecondFunction: function() {
alert('Hi!');
}
}
MyObject.firstFunction();
The above is what you intended to do.
//declaring the constructor
function MyObject() {
this.someProperty = 'whatever';
}
// declaring instance methods
MyObject.prototype = {
firstFunction: function () {
this.secondFunction();
},
secondFunction: function () {
alert("Cool");
}
};
var am = new MyObject();
am.firstFunction();
It's also a good idea to define the methods of your type using the prototype object, which is a property of the constructor function. The value of this
will be the new object that you are trying to initialize.
Upvotes: 1
Reputation: 10251
In this case it's MyObject because it isn't an instance.
If you'ld have done something like:
var MyObject = function() {
};
MyObject.prototype.firstFunction = function() {
this.secondFunction();
};
MyObject.prototype.secondFunction = function() {
console.log('Hi!');
};
var instance = new MyObject();
instance.firstFunction();
Then, you create a new instance and can use this
. In other words: the this
refers to the current instance of an object
Upvotes: 0