If I create a Class with two method like following:
var Car = function() {}
Car.prototype = {
run: function() {
alert('run');
},
stop: function() {
alert('stop');
}
}
And when the DOM is ready will call test() method,
and this test() method will create a instance of Car and call the method of Car
$(document).ready(function() {
test("run");
});
function test(method) {
var instance = new Car();
// call instance.run()
}
I know I have to use apply() method,
but I have tried lots of times and failed
So, how can I use apply() method in Object?
An object in javascript is an associative array, so you can use the
[]operator to address by string any member of the object, functions as well.this will allow to call a function by name over the object Car.
See it working on JsFiddle.
The context inside the called method will properly point to the newly created Car instance without any additional effort, that I guess is what you want. Using
applyorcallis generally used when you need to change the default ‘this‘ value to something else.