Reputation: 2108
I want to send the selector value to the prototype. Currently i am using
var selector; //id of html element
function $(selector)
{
if(window===this)
return new $(selector);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};
It is showing undefined.
Is there any way to pass variable?
Upvotes: 0
Views: 156
Reputation: 664599
No, you cannot access it from the prototype methods. The selector
parameter is a local variable to the constructor.
However, you can make it available as a property on your instance:
function $(selector) {
if(!(this instanceof $))
return new $(selector);
this.selector = selector; // assigns the variable to a property
}
$.prototype.tooltip = function(){
console.log(this.selector); // access the property on the instance
//do calculations with the selector value
return this;
};
Upvotes: 3
Reputation: 234807
I don't see where you are calling any of your functions or setting selector
. However, one problem is that the formal function parameter selector
in your definition of $
masks the outer variable also named selector
. If you eliminate the function parameter, it should work better (assuming that you are also somewhere setting selector
):
var selector; //id of html element
function $()
{
if(window===this)
return new $(selector);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};
The way your code is written now, it is as if it were written as follows:
var selector; //id of html element
function $(x)
{
if(window===this)
return new $(x);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};
Upvotes: 1