Calling method using JavaScript prototype
I did not understand what exactly you're trying to do, but normally implementing object-specific behaviour is done along these lines:
function MyClass(name) {
this.name = name;
}
MyClass.prototype.doStuff = function() {
// generic behaviour
}
var myObj = new MyClass('foo');
var myObjSpecial = new MyClass('bar');
myObjSpecial.doStuff = function() {
// do specialised stuff
// how to call the generic implementation:
MyClass.prototype.doStuff.call(this /*, args...*/);
}
How to call self prototype function in javascript object Constructor
To call function on the current
object you shouldn't use prototype
, just call it(this.say()
).
var Person = (function() {
function Person() {
this.say();
}
Person.prototype.say = function() {
alert("hello");
}
return Person;
})();
var person = new Person();
To learn more about OOP in javascript you can read docs on MDN
Nice doc and examples on MDN for inheritance
and prototype chain
Good notice from @FelixKling
The object
this
refers to doesn't have aprototype
property. Only functions have a prototype property.
Javascript. How I call a prototype method given that methods name as a string plus args?
You want to use bracket notation and apply
scarpa.MyThing.prototype.genericCaller = function(methodName) {
var args = [].slice.call(arguments); //converts arguments to an array
args.shift(); //remove the method name
this[methodName].apply(this, args); //call your method with the current scope and pass the arguments
};
Nice thing with using arguments is you do not have to worry about the d, e, f all the time. You can pass in 20 things and it will still work.
Calling prototype method from another method
Use this code:
vehicleSelect.prototype.getCarMakes = function() {
// Optional parameters
var options = {};
var select = $('#' + this.ID + ' .selMake'),
that = this;
select.on('change', function(e) {
that.getCarModel();
});
// Callback function to be called when the API response is returned
function success(res) {
for (var i=0; i<res.makes.length; i++) {
$("<option>",{
value: res.makes[i].niceName,
html: res.makes[i].name
}).appendTo(select);
}
select.removeAttr("disabled");
select + $(' option[value="placeholder"]').html('Select Make');
}
// Oops, we have a problem!
function fail(data) { console.log(data); }
// Fire the API call
this.res.api('/api/vehicle/v2/makes', options, success, fail);
};
For why you can't just use select.on('change', this.getCarModel)
see this question (which also provides alternative solutions).
Why can't I call a method on the prototype?
You're not creating an instance of the right function! If you look at Test
:
var Test = (function() {
//...
return T;
});
Here, you're assigning Test
to function that returns T
, not T
itself! That's why you can't call a method on the prototype of T
. Instead, use an IIFE:
var Test = (function() {
})(); //Important!
This will assign T
's reference to Test
. Then create a new instance:
new Test();
Calling Javascript prototype method from another method
This seems to do the trick.
Moved all DOM element dependent code into a function that runs after all DOM Content has been loaded.
Added the wheel
event listener on the referenced element
var myScroller;
function Scroller(el) { //Constructor
this.el=el;
this.el.addEventListener('wheel', this.scrolling, { passive: true })
}
Scroller.prototype.scrolling = function(event){ //
console.log(event);
}
window.addEventListener("DOMContentLoaded", function() {
let el = document.getElementById('myElement');
myScroller=new Scroller(el);
})
<div style="width:100px;height:100px;border:1px solid black" id="myElement"></div>
Javascript prototype function calling from typescript
function MyView(x, y) {
//other stuffs
this.initView(x, y); <---- error here
}
MyView.prototype.initView = function(x, y) {
console.log("initView");
}
MyView
is a constructor function.
In order to use this
you should call it with new
keyword
new MyView(2,2)
I'm not sure that you need declare var MyView: any;
call javascript prototype method from another
With your current code, you can just do this:
var p = new Particles();
p.physicsStep();
And, then inside of physicsStep()
, it will appropriately execute this.computeForces()
and this.integrationStep()
and this
will be a pointer to the p
object that was created in the first line of code above.
The value of this
is set by how a method/function is called as described here so if you are having problems with the value of this
, then the issue is likely not in the method itself, but in how it is being called.
If you want help with that part of your code, then can add that code to your question and let us take a look.
Working example: http://jsfiddle.net/jfriend00/yuxppyyf/
Yes, you are correct one problem does have to do with how you are using setInterval.
You can change this:
window.setInterval(particles.physicsStep, 1000 * particles.dt);
to this:
window.setInterval(particles.physicsStep.bind(particles), 1000 * particles.dt);
When you pass particles.physicsStep
as a function reference to another function, the particles
part of that gets lost. All that is passed is a reference to the physicsStep
method so when setInterval then calls it, it is called as an ordinary function, not as a method of your object.
This is a common mistake in Javascript and there are a couple ways to deal with that issue. I showed using .bind()
above. You can also make your own little stub function (which is essentially what .bind()
does for you) like this:
window.setInterval(function() {
particles.physicsStep();
}, 1000 * particles.dt);
This ensures that physicStep()
is called on the right object.
FYI, similar problem and answer here: How to get callback to work with "this" in class scope
Javascript Function.prototype.call()
Let's start with this setup:
function fn() { console.log(this); }
var thisvalue = {fn: fn};
Now you surely understand that thisvalue.fn()
is a method call, and sets the logged this
value to the thisvalue
object.
Next, you seem to know that fn.call(thisvalue)
does exactly the same call. Alternatively, we could write (thisvalue.fn).call(thisvalue)
(parentheses just for structure, could be omitted) as thisvalue.fn === fn
:
thisvalue.fn(…); // is equivalent to
(thisvalue.fn).call(thisvalue, …); // or:
(fn).call(thisvalue, …);
OK, but fn.call(…)
is just a method call as well - the call
method of functions is called on the fn
function.
It can be accessed as such because all function objects inherit this .call
property from Function.prototype
- it's not an own property like .fn
on the thisvalue
object. However, fn.call === Function.prototype.call
is the same as thisvalue.fn === fn
.
Now, we can rewrite that method call of .call
as an explicit invocation with .call()
:
fn.call(thisvalue); // is equivalent to
(fn.call).call(fn, thisvalue); // or:
(Function.protoype.call).call(fn, thisvalue);
I hope you spot the pattern and can now explain why the following work as well:
Function.prototype.call.call.call(Function.prototype.call, fn, thisvalue);
var call = Function.prototype.call; call.call(call, fn, thisvalue);
Breaking this down is left as an exercise to the reader :-)
Related Topics
How to Sort/Order Keys in JavaScript Objects
How to Disable Right-Click Context-Menu in JavaScript
How to Access Parent Window Object Using Jquery
What's a Good Tool to Screen-Scrape with JavaScript Support
How to Get the Exact Local Time of Client
Is There a Generic Way to Set State in React Hooks? How to Manage Multiple States
How to Make a Div Element Editable (Like a Textarea When I Click It)
How to Prevent Moment.Js from Loading Locales with Webpack
Passing Variables to the Next Middleware Using Next() in Express.Js
How to Load Image Files with Webpack File-Loader
What the Difference Between .Click and .Change on a Checkbox
Copy to Clipboard in Chrome Extension
Open Page in New Window Without Popup Blocking
How Is a Promise/Defer Library Implemented