var Ob = function(){
}
Ob.prototype.add = function(){
inc()
}
Ob.prototype.inc = function(){
alert(' Inc called ');
}
window.onload = function(){
var o = new Ob();
o.add();
}
I would like to call something like this,how can i call, ofcourse i put inc as inner function to add I can do that but without having the inner function. how do i do that ?
It's easy:
Ob.prototype.add = function(){
this.inc()
}
Ob.prototype.inc = function(){
alert(' Inc called ');
}
When you create the instance of Ob properties from prototype are copied to the object. If you want to access the methods of instance from within its another method you could use this.
Related
I can't get how to access that value, this is my code:
function Filters()
{
this.filters = ["filter_1", "filter_2", "filter_3"];
this.someData = "test";
this.draw = draw;
function draw(){
for(var i=0; i<this.filters.length;i++)
{
var filter = this.filters[i];
$("#" + filter).click(function(){
doSomething();
});
}
}
function doSomething(){
alert(this.someData);
}
}
I am aware of the fact that since doSomething() is called from within the closure, this. will refer a JQuery object being worked on. So how do I go about being able to use someData from my object in that function/closure ? Can't seem to figure it out.
Thanks for help :)
No, this inside doSomething will be the global object. You need to keep a reference to this in a separate variable:
function Filters()
{
var that = this; // reference to this
this.filters = ["filter_1", "filter_2", "filter_3"];
this.someData = "test";
this.draw = draw;
function draw(){
for(var i=0; i<this.filters.length;i++)
{
var filter = this.filters[i];
$("#" + filter).click(function(){
doSomething();
});
}
}
function doSomething(){
alert(that.someData);
}
}
Unrelated to your problem: you could also pass a reference to doSomething as the event listener, instead of wrapping it in another function:
$("#" + filter).click(doSomething);
The code is pretty explanatory. What I am doing is wrong. How can I access the a property of the A object in the onclick event of an object declared inside of an A object method?
function A(){
this.a = 0;
};
A.prototype.myfun= function(){
var b = document.getElementsByClassName("myclassName");
b[0].onclick = function(e){
//How can I get the a property of the A object in here?
this.a = 1;
}
};
Could I somehow pass this as an argument like this?
b[0].onclick = function(e, this){
Since this in a function references to the function itself, you could do 2 things. Pass around the reference, or create a variable you won't overwrite that represents the this
function A(){
this.a = 0;
};
A.prototype.myfun= function(){
var self = this;
var b = document.getElementsByClassName("myclassName");
b[0].onclick = function(e){
self.a = 1;
}
};
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I have the following Javascript code, and I'm trying to get a callback to work as shown below. I want to see an alert with "123" in it.
var A = function(arg){
this.storedArg = arg;
this.callback = function(){ alert(this.storedArg); }
}
var B = function() {
this.doCallback = function(callback){ callback(); }
}
var pubCallback = function(){ alert('Public callback') };
var a = new A(123);
var b = new B();
b.doCallback(pubCallback); // works as expected
b.doCallback(a.callback); // want 123, get undefined
I understand what is happening but I'm not sure how to fix it. How can I get a callback function that references my a object? In my case, I can make changes to A but not B.
So what you want is to pass the context to the doCallBack.
E.g.
doCallBack = function (callback, callee) {
callback.apply(callee);
}
So then you would do:
b.doCallBack(a.callback, a);
If you cannot modify the B then you can use closure inside A:
var A = function (arg) {
var self = this;
this.storedArg = arg;
this.callback = function () { alert(self.storedArg); }
}
You can create a variable that holds the wanted scope for this by putting it into variable that
var A = function(arg){
this.storedArg = arg;
var that = this; // Add this!
this.callback = function(){ alert(that.storedArg); }
}
Working demo here: http://jsfiddle.net/vdM5t/
I understand what is happening (during the 2nd callback, "this" is b and not a)
No, JS is no class-based language where something could happen. If function(){ alert(this.storedArg); is just called as callback(); (like in b.doCallback), the this keyword points to the global object (window).
To get around that, you'd have to change A to
var A = function(arg){
var that = this; // store reference to the current A object
this.storedArg = arg;
this.callback = function(){
alert(that.storedArg); // and use that reference now instead of "this"
};
}
If you don't expect the storedArg property to change, you could even make it more simple:
var A = function(arg){
this.storedArg = arg;
this.callback = function(){
alert(arg); // just use the argument of the A function,
// which is still in the variable scope
};
}
You need to pass the context you want the callback to execute in:
var B = function() {
this.doCallback = function(callback, context) {
callback.apply(context);
};
};
b.doCallback(a.callback, a); // 123
http://jsfiddle.net/a9N66/
Because inside A.callback function, this does not refer to A but to window object.
var A = function(arg){
this.storedArg = arg;
this.callback = function(){ alert(this.storedArg); }
-----------------------------------^-----------------
}
You can try this,
var A = function(arg){
this.storedArg = arg;
var that = this;
this.callback = function(){ alert(that.storedArg); }
}
var B = function() {
this.doCallback = function(callback){ callback(); }
}
var pubCallback = function(){ alert('Public callback') };
var a = new A(123);
var b = new B();
b.doCallback(pubCallback); // works as expected
b.doCallback(a.callback); // alerts 123
When you do this:
b.doCallback(a.callback);
that just calls a's callback function without telling it to use a for this; so the global object is used for this.
One solution is to wrap that callback up:
b.doCallback(function() { a.callback(); });
Other solutions include binding the callback to a, using jQuery.proxy() (which is just a fancy way of doing my first solution), or passing in a to doCallback and invoking callback on a using apply.
...
$.fn.annotateEdit = function(image, note) {
if (note) {
this.note = note;
} else {
var newNote = new Object();
newNote.id = "new";
this.note = newNote;
}
}
...
var mynote = this.note;
form.find(':radio').change(function() {
var vacancy = $(this).attr('value');
mynote.vacancy = vacancy;
});
...
Is it possible to access "this.note" from the change() handler without defining "mynote"?
I use a pattern like this so I can access anything in the enclosing scope:
var that = this;
...
form.find(':radio').change(function () {
that.note.vacancy = $(this).attr('value');
});
I am a fan of this pattern because it makes the code a little more readable. In my opinion, it is clear what it being accessed is part of the enclosing scope (as long as the usage of that is consistent).
Use $.proxy to bind it to a function...
// Returns a function-------v
form.find(':radio').change( $.proxy(function() {
var vacancy = $(this).attr('value');
mynote.vacancy = vacancy;
}, this) );
// ^---- ...that has its "this" value set as this argument.
There is no dedicated language mechanism for it. The common pattern is to store the this in local (closure) variable (often named self or that) of the outer function:
var self = this;
var innerFunction = function() {
self.x = 1;
};
Check this - http://api.jquery.com/bind/ and "Passing event data"
You can do something like this :
form.find(':radio').bind("change", {
context : this
}, function(event){
console.log(event.data.context);
console.log(event.data.context.note);
});
You can bind the context of the parent object like so.
form.find(':radio').change(function(that) {
var vacancy = $(this).attr('value');
that.note.vacancy = vacancy;
}.bind(null,this));
I'm wondering if any of yall have any insight as to how one could execute a function by reference in javascript.
http://mootools.net/shell/yL93N/1/
Any discussion would be cool.
-Chase
looking at your mooshell, the way i'd handle it in mootools is this:
http://mootools.net/shell/yL93N/10/
var proxyFunction = new Class({
message: "hello",
Binds: ['passByReference','sayit'],
passByReference: function(func) {
// console.log(this, this[func]);
if (this[func] && $type(this[func]) === "function")
this[func]();
},
sayit: function() {
alert(this.message);
},
killit: function() {
document.write('we\'re dead');
}
});
$('tryit').addEvent('change',function(e){
new proxyFunction().passByReference(this.get('value'));
});
// or have a permanent proxy instance if you call methods of the class often and need it to change things.
var proxy = new proxyFunction();
$('tryit').addEvent('change',function(e){
proxy.passByReference(this.get('value'));
});
the advantage of doing so is that all your proxied functions are behind a common object, don't pollute your window namespace as global variables and can share data that relates to the event.
Not exactly sure what you mean, but you can do this:
var func = window.alert;
var args = ["hello world"]
func.apply(window, args)
Globally-defined functions (and variables) are visible as members of the global window object.
Members of an object can be fetched by name using the square bracket notation: o['k'] is the same as o.k. So, for your example:
var function_name= $(this).val();
window[function_name]();
Like this?
function blah() {
...do stuff
}
myref = blah
myref()
The best way is to do:
func.call();
Function variables in JavaScript already are references. If you have a function:
var explode = function() { alert('boom!'); };
You can pass explode around as an argument, and it's only passing a handle to that function, not the entire function body.
For proof of this, try:
explode.id = 5;
var detonate = explode;
alert(detonate.id); // => 5
explode.id = 6;
alert(detonate.id); // => 6
functions are first class objects in Java Script. Effectively this means that you can treat it very much as if it were a variable, and pass it anywhere that you would expect a variable.
e.g.
var myFn = function() { alert('inside anonymous fn'); }
function callMyFn(paramFn)
{
paramFn();
}
callMyFn(myFn); //inside anonymous fn
function MyFnHolders(argFn)
{
this.argFn = argFn;
this.fieldFn = function() {
alert('inside fn field');
}
}
var myFnHolders = new MyFnHolders(myFn);
myFnHolders.argFn(); //'inside anonymous fn'
myFnHolders.fieldFn(); //'inside fn field'
//etc
so passing a function by ref can be done simply by assigning it to a variable and passing it around.
Here's one with a closure for your arguments...
function Runner(func, args) {
return function() { return func.apply(window, args); };
}
var ref = new Runner(window.alert, ["hello world"]);
ref();